class e{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}const t=new e;class i{constructor(e){this.id=e,this.parentItem=null,this.groups=[],this.menuElement=null,this.shown=!1,this.mouseOver=0}}class s{constructor(){this.items=[]}}class r{constructor(e,t,i,s){this.id=e,this.getTitle=t,this.doAction=i,this.getEnabled=s,this.itemElement=null,this.subMenu=null,this.enabled=!0}}class o{constructor(e={}){this._id=t.addItem(),this._context=null,this._enabled=!1,this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={},this._shown=!1,this._nextId=0,this._eventSubs={},!1!==e.hideOnMouseDown&&document.addEventListener("mousedown",(e=>{e.target.classList.contains("xeokit-context-menu-item")||this.hide()})),e.items&&(this.items=e.items),this.context=e.context,this.enabled=!1!==e.enabled,this.hide()}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}set items(e){this._clear(),this._itemsCfg=e||[],this._parseItems(e),this._createUI()}get items(){return this._itemsCfg}set enabled(e){(e=!!e)!==this._enabled&&(this._enabled=e,this._enabled||this.hide())}get enabled(){return this._enabled}set context(e){this._context=e}get context(){return this._context}show(e,t){this._context?this._enabled&&(this._shown||(this._hideAllMenus(),this._updateItemsTitles(),this._updateItemsEnabledStatus(),this._showMenu(this._rootMenu.id,e,t),this._shown=!0,this.fire("shown",{}))):console.error("ContextMenu cannot be shown without a context - set context first")}get shown(){return this._shown}hide(){this._enabled&&this._shown&&(this._hideAllMenus(),this._shown=!1,this.fire("hidden",{}))}destroy(){this._context=null,this._clear(),null!==this._id&&(t.removeItem(this._id),this._id=null)}_clear(){for(let e=0,t=this._menuList.length;e<t;e++){const t=this._menuList[e].menuElement;t.parentElement.removeChild(t)}this._itemsCfg=[],this._rootMenu=null,this._menuList=[],this._menuMap={},this._itemList=[],this._itemMap={}}_parseItems(e){const t=e=>{const o=this._getNextId(),a=new i(o);for(let i=0,o=e.length;i<o;i++){const o=e[i],n=new s;a.groups.push(n);for(let e=0,i=o.length;e<i;e++){const i=o[e],s=i.items,l=s&&s.length>0,h=this._getNextId(),c=i.getTitle||(()=>i.title||""),u=i.doAction||i.callback||(()=>{}),d=i.getEnabled||(()=>!0),p=new r(h,c,u,d);if(p.parentMenu=a,n.items.push(p),l){const e=t(s);p.subMenu=e,e.parentItem=p}this._itemList.push(p),this._itemMap[p.id]=p}}return this._menuList.push(a),this._menuMap[a.id]=a,a};this._rootMenu=t(e)}_getNextId(){return"ContextMenu_"+this._id+this._nextId++}_createUI(){const e=t=>{this._createMenuUI(t);const i=t.groups;for(let t=0,s=i.length;t<s;t++){const s=i[t].items;for(let t=0,i=s.length;t<i;t++){const i=s[t].subMenu;i&&e(i)}}};e(this._rootMenu)}_createMenuUI(e){const t=e.groups,i=[];if(i.push('<div class="xeokit-context-menu '+e.id+'" style="z-index:300000; position: absolute;">'),i.push("<ul>"),t)for(let e=0,s=t.length;e<s;e++){const r=e,o=s,a=t[e].items;if(a)for(let e=0,t=a.length;e<t;e++){const s=a[e],n=s.subMenu,l=s.title||"";n?i.push('<li id="'+s.id+'" class="xeokit-context-menu-item" style="'+(r===o-1||e<t-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+l+" [MORE]</li>"):i.push('<li id="'+s.id+'" class="xeokit-context-menu-item" style="'+(r===o-1||e<t-1?"border-bottom: 0":"border-bottom: 1px solid black")+'">'+l+"</li>")}}i.push("</ul>"),i.push("</div>");const s=i.join("");document.body.insertAdjacentHTML("beforeend",s);const r=document.querySelector("."+e.id);e.menuElement=r,r.style["border-radius"]="4px",r.style.display="none",r.style["z-index"]=3e5,r.style.background="white",r.style.border="1px solid black",r.style["box-shadow"]="0 4px 5px 0 gray",r.oncontextmenu=e=>{e.preventDefault()};const o=this;let a=null;if(t)for(let e=0,i=t.length;e<i;e++){const i=t[e].items;if(i)for(let e=0,t=i.length;e<t;e++){const t=i[e],s=t.subMenu;t.itemElement=document.getElementById(t.id),t.itemElement?(t.itemElement.addEventListener("mouseenter",(e=>{if(e.preventDefault(),!1===t.enabled)return;const i=t.subMenu;if(!i)return void(a&&(o._hideMenu(a.id),a=null));a&&a.id!==i.id&&(o._hideMenu(a.id),a=null);const s=t.itemElement,r=i.menuElement,n=s.getBoundingClientRect();r.getBoundingClientRect(),n.right+200>window.innerWidth?o._showMenu(i.id,n.left-200,n.top-1):o._showMenu(i.id,n.right-5,n.top-1),a=i})),s||(t.itemElement.addEventListener("click",(e=>{e.preventDefault(),o.hide(),o._context&&!1!==t.enabled&&t.doAction&&t.doAction(o._context)})),t.itemElement.addEventListener("mouseenter",(e=>{e.preventDefault(),!1!==t.enabled&&t.doHover&&t.doHover(o._context)})))):console.error("ContextMenu item element not found: "+t.id)}}}_updateItemsTitles(){if(this._context)for(let e=0,t=this._itemList.length;e<t;e++){const t=this._itemList[e],i=t.itemElement;if(!i)continue;const s=t.getTitle(this._context);t.subMenu,i.innerText=s}}_updateItemsEnabledStatus(){if(this._context)for(let e=0,t=this._itemList.length;e<t;e++){const t=this._itemList[e],i=t.itemElement;if(!i)continue;const s=t.getEnabled;if(!s)continue;const r=s(this._context);t.enabled=r,r?i.classList.remove("disabled"):i.classList.add("disabled")}}_showMenu(e,t,i){const s=this._menuMap[e];if(!s)return void console.error("Menu not found: "+e);if(s.shown)return;const r=s.menuElement;r&&(this._showMenuElement(r,t,i),s.shown=!0)}_hideMenu(e){const t=this._menuMap[e];if(!t)return void console.error("Menu not found: "+e);if(!t.shown)return;const i=t.menuElement;i&&(this._hideMenuElement(i),t.shown=!1)}_hideAllMenus(){for(let e=0,t=this._menuList.length;e<t;e++){const t=this._menuList[e];this._hideMenu(t.id)}}_showMenuElement(e,t,i){e.style.display="block";const s=e.offsetHeight,r=e.offsetWidth;i+s>window.innerHeight&&(i=window.innerHeight-s),t+r>window.innerWidth&&(t=window.innerWidth-r),e.style.left=t+"px",e.style.top=i+"px"}_hideMenuElement(e){e.style.display="none"}}class a{constructor(e,t,i){this.id=i&&i.id?i.id:e,this.viewer=t,this._eventSubs={},t.addPlugin(this)}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}log(e){console.log(`[xeokit plugin ${this.id}]: ${e}`)}warn(e){console.warn(`[xeokit plugin ${this.id}]: ${e}`)}error(e){console.error(`[xeokit plugin ${this.id}]: ${e}`)}send(e,t){}destroy(){this.viewer.removePlugin(this)}}const n=Float64Array,l=new n(16),h=new n(16),c=new n(4),u={MIN_DOUBLE:-Number.MAX_SAFE_INTEGER,MAX_DOUBLE:Number.MAX_SAFE_INTEGER,DEGTORAD:.0174532925,RADTODEG:57.295779513,unglobalizeObjectId(e,t){const i=t.indexOf("#");return i===e.length&&t.startsWith(e)?t.substring(i+1):t},globalizeObjectId:(e,t)=>e+"#"+t,vec2:e=>new n(e||2),vec3:e=>new n(e||3),vec4:e=>new n(e||4),mat3:e=>new n(e||9),mat3ToMat4:(e,t=new n(16))=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=0,t[4]=e[3],t[5]=e[4],t[6]=e[5],t[7]=0,t[8]=e[6],t[9]=e[7],t[10]=e[8],t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t),mat4:e=>new n(e||16),mat4ToMat3(e,t){},doublesToFloats(e,t,i){const s=new Float32Array(2);for(let r=0,o=e.length;r<o;r++)u.splitDouble(e[r],s),t[r]=s[0],i[r]=s[1]},splitDouble(e,t){const i=Float32Array.from([e])[0],s=e-i;t[0]=i,t[1]=s},createUUID:(()=>{const e=[];for(let t=0;t<256;t++)e[t]=(t<16?"0":"")+t.toString(16);return()=>{const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,r=4294967295*Math.random()|0;return`${e[255&t]+e[t>>8&255]+e[t>>16&255]+e[t>>24&255]}-${e[255&i]}${e[i>>8&255]}-${e[i>>16&15|64]}${e[i>>24&255]}-${e[63&s|128]}${e[s>>8&255]}-${e[s>>16&255]}${e[s>>24&255]}${e[255&r]}${e[r>>8&255]}${e[r>>16&255]}${e[r>>24&255]}`}})(),clamp:(e,t,i)=>Math.max(t,Math.min(i,e)),fmod(e,t){if(e<t)return console.error("math.fmod : Attempting to find modulus within negative range - would be infinite loop - ignoring"),e;for(;t<=e;)e-=t;return e},compareVec3:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2],negateVec3:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t),negateVec4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t),addVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i),addVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i),addVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i),addVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i),subVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i),subVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i),subVec2:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i),geometricMeanVec2(...e){const t=new n(e[0]);for(let i=1;i<e.length;i++)t[0]+=e[i][0],t[1]+=e[i][1];return t[0]/=e.length,t[1]/=e.length,t},subVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i),subScalarVec4:(e,t,i)=>(i||(i=e),i[0]=t-e[0],i[1]=t-e[1],i[2]=t-e[2],i[3]=t-e[3],i),mulVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]*t[0],i[1]=e[1]*t[1],i[2]=e[2]*t[2],i[3]=e[3]*t[3],i),mulVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i),mulVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i),mulVec2Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i),divVec3:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i),divVec4:(e,t,i)=>(i||(i=e),i[0]=e[0]/t[0],i[1]=e[1]/t[1],i[2]=e[2]/t[2],i[3]=e[3]/t[3],i),divScalarVec3:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i),divVec3Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i),divVec4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]/t,i[1]=e[1]/t,i[2]=e[2]/t,i[3]=e[3]/t,i),divScalarVec4:(e,t,i)=>(i||(i=t),i[0]=e/t[0],i[1]=e/t[1],i[2]=e/t[2],i[3]=e/t[3],i),dotVec4:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2]+e[3]*t[3],cross3Vec4(e,t){const i=e[0],s=e[1],r=e[2],o=t[0],a=t[1],n=t[2];return[s*n-r*a,r*o-i*n,i*a-s*o,0]},cross3Vec3(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],a=t[0],n=t[1],l=t[2];return i[0]=r*l-o*n,i[1]=o*a-s*l,i[2]=s*n-r*a,i},sqLenVec4:e=>u.dotVec4(e,e),lenVec4:e=>Math.sqrt(u.sqLenVec4(e)),dotVec3:(e,t)=>e[0]*t[0]+e[1]*t[1]+e[2]*t[2],dotVec2:(e,t)=>e[0]*t[0]+e[1]*t[1],sqLenVec3:e=>u.dotVec3(e,e),sqLenVec2:e=>u.dotVec2(e,e),lenVec3:e=>Math.sqrt(u.sqLenVec3(e)),distVec3:(()=>{const e=new n(3);return(t,i)=>u.lenVec3(u.subVec3(t,i,e))})(),lenVec2:e=>Math.sqrt(u.sqLenVec2(e)),distVec2:(()=>{const e=new n(2);return(t,i)=>u.lenVec2(u.subVec2(t,i,e))})(),rcpVec3:(e,t)=>u.divScalarVec3(1,e,t),normalizeVec4(e,t){const i=1/u.lenVec4(e);return u.mulVec4Scalar(e,i,t)},normalizeVec3(e,t){const i=1/u.lenVec3(e);return u.mulVec3Scalar(e,i,t)},normalizeVec2(e,t){const i=1/u.lenVec2(e);return u.mulVec2Scalar(e,i,t)},angleVec3(e,t){let i=u.dotVec3(e,t)/Math.sqrt(u.sqLenVec3(e)*u.sqLenVec3(t));return i=i<-1?-1:i>1?1:i,Math.acos(i)},vec3FromMat4Scale:(()=>{const e=new n(3);return(t,i)=>(e[0]=t[0],e[1]=t[1],e[2]=t[2],i[0]=u.lenVec3(e),e[0]=t[4],e[1]=t[5],e[2]=t[6],i[1]=u.lenVec3(e),e[0]=t[8],e[1]=t[9],e[2]=t[10],i[2]=u.lenVec3(e),i)})(),vecToArray:(()=>{function e(e){return Math.round(1e5*e)/1e5}return t=>{for(let i=0,s=(t=Array.prototype.slice.call(t)).length;i<s;i++)t[i]=e(t[i]);return t}})(),xyzArrayToObject:e=>({x:e[0],y:e[1],z:e[2]}),xyzObjectToArray:(e,t)=>((t=t||new n(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t),dupMat4:e=>e.slice(0,16),mat4To3:e=>[e[0],e[1],e[2],e[4],e[5],e[6],e[8],e[9],e[10]],m4s:e=>[e,e,e,e,e,e,e,e,e,e,e,e,e,e,e,e],setMat4ToZeroes:()=>u.m4s(0),setMat4ToOnes:()=>u.m4s(1),diagonalMat4v:e=>new n([e[0],0,0,0,0,e[1],0,0,0,0,e[2],0,0,0,0,e[3]]),diagonalMat4c:(e,t,i,s)=>u.diagonalMat4v([e,t,i,s]),diagonalMat4s:e=>u.diagonalMat4c(e,e,e,e),identityMat4:(e=new n(16))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=0,e[5]=1,e[6]=0,e[7]=0,e[8]=0,e[9]=0,e[10]=1,e[11]=0,e[12]=0,e[13]=0,e[14]=0,e[15]=1,e),identityMat3:(e=new n(9))=>(e[0]=1,e[1]=0,e[2]=0,e[3]=0,e[4]=1,e[5]=0,e[6]=0,e[7]=0,e[8]=1,e),isIdentityMat4:e=>1===e[0]&&0===e[1]&&0===e[2]&&0===e[3]&&0===e[4]&&1===e[5]&&0===e[6]&&0===e[7]&&0===e[8]&&0===e[9]&&1===e[10]&&0===e[11]&&0===e[12]&&0===e[13]&&0===e[14]&&1===e[15],negateMat4:(e,t)=>(t||(t=e),t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=-e[3],t[4]=-e[4],t[5]=-e[5],t[6]=-e[6],t[7]=-e[7],t[8]=-e[8],t[9]=-e[9],t[10]=-e[10],t[11]=-e[11],t[12]=-e[12],t[13]=-e[13],t[14]=-e[14],t[15]=-e[15],t),addMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]+t[0],i[1]=e[1]+t[1],i[2]=e[2]+t[2],i[3]=e[3]+t[3],i[4]=e[4]+t[4],i[5]=e[5]+t[5],i[6]=e[6]+t[6],i[7]=e[7]+t[7],i[8]=e[8]+t[8],i[9]=e[9]+t[9],i[10]=e[10]+t[10],i[11]=e[11]+t[11],i[12]=e[12]+t[12],i[13]=e[13]+t[13],i[14]=e[14]+t[14],i[15]=e[15]+t[15],i),addMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]+t,i[1]=e[1]+t,i[2]=e[2]+t,i[3]=e[3]+t,i[4]=e[4]+t,i[5]=e[5]+t,i[6]=e[6]+t,i[7]=e[7]+t,i[8]=e[8]+t,i[9]=e[9]+t,i[10]=e[10]+t,i[11]=e[11]+t,i[12]=e[12]+t,i[13]=e[13]+t,i[14]=e[14]+t,i[15]=e[15]+t,i),addScalarMat4:(e,t,i)=>u.addMat4Scalar(t,e,i),subMat4:(e,t,i)=>(i||(i=e),i[0]=e[0]-t[0],i[1]=e[1]-t[1],i[2]=e[2]-t[2],i[3]=e[3]-t[3],i[4]=e[4]-t[4],i[5]=e[5]-t[5],i[6]=e[6]-t[6],i[7]=e[7]-t[7],i[8]=e[8]-t[8],i[9]=e[9]-t[9],i[10]=e[10]-t[10],i[11]=e[11]-t[11],i[12]=e[12]-t[12],i[13]=e[13]-t[13],i[14]=e[14]-t[14],i[15]=e[15]-t[15],i),subMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]-t,i[1]=e[1]-t,i[2]=e[2]-t,i[3]=e[3]-t,i[4]=e[4]-t,i[5]=e[5]-t,i[6]=e[6]-t,i[7]=e[7]-t,i[8]=e[8]-t,i[9]=e[9]-t,i[10]=e[10]-t,i[11]=e[11]-t,i[12]=e[12]-t,i[13]=e[13]-t,i[14]=e[14]-t,i[15]=e[15]-t,i),subScalarMat4:(e,t,i)=>(i||(i=t),i[0]=e-t[0],i[1]=e-t[1],i[2]=e-t[2],i[3]=e-t[3],i[4]=e-t[4],i[5]=e-t[5],i[6]=e-t[6],i[7]=e-t[7],i[8]=e-t[8],i[9]=e-t[9],i[10]=e-t[10],i[11]=e-t[11],i[12]=e-t[12],i[13]=e-t[13],i[14]=e-t[14],i[15]=e-t[15],i),mulMat4(e,t,i){i||(i=e);const s=e[0],r=e[1],o=e[2],a=e[3],n=e[4],l=e[5],h=e[6],c=e[7],u=e[8],d=e[9],p=e[10],_=e[11],f=e[12],g=e[13],m=e[14],v=e[15],b=t[0],P=t[1],y=t[2],M=t[3],x=t[4],w=t[5],E=t[6],A=t[7],C=t[8],S=t[9],D=t[10],L=t[11],B=t[12],T=t[13],R=t[14],F=t[15];return i[0]=b*s+P*n+y*u+M*f,i[1]=b*r+P*l+y*d+M*g,i[2]=b*o+P*h+y*p+M*m,i[3]=b*a+P*c+y*_+M*v,i[4]=x*s+w*n+E*u+A*f,i[5]=x*r+w*l+E*d+A*g,i[6]=x*o+w*h+E*p+A*m,i[7]=x*a+w*c+E*_+A*v,i[8]=C*s+S*n+D*u+L*f,i[9]=C*r+S*l+D*d+L*g,i[10]=C*o+S*h+D*p+L*m,i[11]=C*a+S*c+D*_+L*v,i[12]=B*s+T*n+R*u+F*f,i[13]=B*r+T*l+R*d+F*g,i[14]=B*o+T*h+R*p+F*m,i[15]=B*a+T*c+R*_+F*v,i},mulMat3(e,t,i){i||(i=new n(9));const s=e[0],r=e[3],o=e[6],a=e[1],l=e[4],h=e[7],c=e[2],u=e[5],d=e[8],p=t[0],_=t[3],f=t[6],g=t[1],m=t[4],v=t[7],b=t[2],P=t[5],y=t[8];return i[0]=s*p+r*g+o*b,i[3]=s*_+r*m+o*P,i[6]=s*f+r*v+o*y,i[1]=a*p+l*g+h*b,i[4]=a*_+l*m+h*P,i[7]=a*f+l*v+h*y,i[2]=c*p+u*g+d*b,i[5]=c*_+u*m+d*P,i[8]=c*f+u*v+d*y,i},mulMat4Scalar:(e,t,i)=>(i||(i=e),i[0]=e[0]*t,i[1]=e[1]*t,i[2]=e[2]*t,i[3]=e[3]*t,i[4]=e[4]*t,i[5]=e[5]*t,i[6]=e[6]*t,i[7]=e[7]*t,i[8]=e[8]*t,i[9]=e[9]*t,i[10]=e[10]*t,i[11]=e[11]*t,i[12]=e[12]*t,i[13]=e[13]*t,i[14]=e[14]*t,i[15]=e[15]*t,i),mulMat4v4(e,t,i=u.vec4()){const s=t[0],r=t[1],o=t[2],a=t[3];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*a,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*a,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*a,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*a,i},transposeMat4(e,t){const i=e[4],s=e[14],r=e[8],o=e[13],a=e[12],n=e[9];if(!t||e===t){const t=e[1],l=e[2],h=e[3],c=e[6],u=e[7],d=e[11];return e[1]=i,e[2]=r,e[3]=a,e[4]=t,e[6]=n,e[7]=o,e[8]=l,e[9]=c,e[11]=s,e[12]=h,e[13]=u,e[14]=d,e}return t[0]=e[0],t[1]=i,t[2]=r,t[3]=a,t[4]=e[1],t[5]=e[5],t[6]=n,t[7]=o,t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=s,t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15],t},transposeMat3(e,t){if(t===e){const i=e[1],s=e[2],r=e[5];t[1]=e[3],t[2]=e[6],t[3]=i,t[5]=e[7],t[6]=s,t[7]=r}else t[0]=e[0],t[1]=e[3],t[2]=e[6],t[3]=e[1],t[4]=e[4],t[5]=e[7],t[6]=e[2],t[7]=e[5],t[8]=e[8];return t},determinantMat4(e){const t=e[0],i=e[1],s=e[2],r=e[3],o=e[4],a=e[5],n=e[6],l=e[7],h=e[8],c=e[9],u=e[10],d=e[11],p=e[12],_=e[13],f=e[14],g=e[15];return p*c*n*r-h*_*n*r-p*a*u*r+o*_*u*r+h*a*f*r-o*c*f*r-p*c*s*l+h*_*s*l+p*i*u*l-t*_*u*l-h*i*f*l+t*c*f*l+p*a*s*d-o*_*s*d-p*i*n*d+t*_*n*d+o*i*f*d-t*a*f*d-h*a*s*g+o*c*s*g+h*i*n*g-t*c*n*g-o*i*u*g+t*a*u*g},inverseMat4(e,t){t||(t=e);const i=e[0],s=e[1],r=e[2],o=e[3],a=e[4],n=e[5],l=e[6],h=e[7],c=e[8],u=e[9],d=e[10],p=e[11],_=e[12],f=e[13],g=e[14],m=e[15],v=i*n-s*a,b=i*l-r*a,P=i*h-o*a,y=s*l-r*n,M=s*h-o*n,x=r*h-o*l,w=c*f-u*_,E=c*g-d*_,A=c*m-p*_,C=u*g-d*f,S=u*m-p*f,D=d*m-p*g,L=1/(v*D-b*S+P*C+y*A-M*E+x*w);return t[0]=(n*D-l*S+h*C)*L,t[1]=(-s*D+r*S-o*C)*L,t[2]=(f*x-g*M+m*y)*L,t[3]=(-u*x+d*M-p*y)*L,t[4]=(-a*D+l*A-h*E)*L,t[5]=(i*D-r*A+o*E)*L,t[6]=(-_*x+g*P-m*b)*L,t[7]=(c*x-d*P+p*b)*L,t[8]=(a*S-n*A+h*w)*L,t[9]=(-i*S+s*A-o*w)*L,t[10]=(_*M-f*P+m*v)*L,t[11]=(-c*M+u*P-p*v)*L,t[12]=(-a*C+n*E-l*w)*L,t[13]=(i*C-s*E+r*w)*L,t[14]=(-_*y+f*b-g*v)*L,t[15]=(c*y-u*b+d*v)*L,t},traceMat4:e=>e[0]+e[5]+e[10]+e[15],translationMat4v(e,t){const i=t||u.identityMat4();return i[12]=e[0],i[13]=e[1],i[14]=e[2],i},translationMat3v(e,t){const i=t||u.identityMat3();return i[6]=e[0],i[7]=e[1],i},translationMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,u.translationMat4v(e,r))})(),translationMat4s:(e,t)=>u.translationMat4c(e,e,e,t),translateMat4v:(e,t)=>u.translateMat4c(e[0],e[1],e[2],t),OLDtranslateMat4c(e,t,i,s){const r=s[12];s[0]+=r*e,s[4]+=r*t,s[8]+=r*i;const o=s[13];s[1]+=o*e,s[5]+=o*t,s[9]+=o*i;const a=s[14];s[2]+=a*e,s[6]+=a*t,s[10]+=a*i;const n=s[15];return s[3]+=n*e,s[7]+=n*t,s[11]+=n*i,s},translateMat4c(e,t,i,s){const r=s[3];s[0]+=r*e,s[1]+=r*t,s[2]+=r*i;const o=s[7];s[4]+=o*e,s[5]+=o*t,s[6]+=o*i;const a=s[11];s[8]+=a*e,s[9]+=a*t,s[10]+=a*i;const n=s[15];return s[12]+=n*e,s[13]+=n*t,s[14]+=n*i,s},setMat4Translation:(e,t,i)=>(i[0]=e[0],i[1]=e[1],i[2]=e[2],i[3]=e[3],i[4]=e[4],i[5]=e[5],i[6]=e[6],i[7]=e[7],i[8]=e[8],i[9]=e[9],i[10]=e[10],i[11]=e[11],i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=e[15],i),rotationMat4v(e,t,i){const s=u.normalizeVec4([t[0],t[1],t[2],0],[]),r=Math.sin(e),o=Math.cos(e),a=1-o,n=s[0],l=s[1],h=s[2];let c,d,p,_,f,g;return c=n*l,d=l*h,p=h*n,_=n*r,f=l*r,g=h*r,(i=i||u.mat4())[0]=a*n*n+o,i[1]=a*c+g,i[2]=a*p-f,i[3]=0,i[4]=a*c-g,i[5]=a*l*l+o,i[6]=a*d+_,i[7]=0,i[8]=a*p+f,i[9]=a*d-_,i[10]=a*h*h+o,i[11]=0,i[12]=0,i[13]=0,i[14]=0,i[15]=1,i},rotationMat4c:(e,t,i,s,r)=>u.rotationMat4v(e,[t,i,s],r),scalingMat4v:(e,t=u.identityMat4())=>(t[0]=e[0],t[5]=e[1],t[10]=e[2],t),scalingMat3v:(e,t=u.identityMat3())=>(t[0]=e[0],t[4]=e[1],t),scalingMat4c:(()=>{const e=new n(3);return(t,i,s,r)=>(e[0]=t,e[1]=i,e[2]=s,u.scalingMat4v(e,r))})(),scaleMat4c:(e,t,i,s)=>(s[0]*=e,s[4]*=t,s[8]*=i,s[1]*=e,s[5]*=t,s[9]*=i,s[2]*=e,s[6]*=t,s[10]*=i,s[3]*=e,s[7]*=t,s[11]*=i,s),scaleMat4v(e,t){const i=e[0],s=e[1],r=e[2];return t[0]*=i,t[4]*=s,t[8]*=r,t[1]*=i,t[5]*=s,t[9]*=r,t[2]*=i,t[6]*=s,t[10]*=r,t[3]*=i,t[7]*=s,t[11]*=r,t},scalingMat4s:e=>u.scalingMat4c(e,e,e),rotationTranslationMat4(e,t,i=u.mat4()){const s=e[0],r=e[1],o=e[2],a=e[3],n=s+s,l=r+r,h=o+o,c=s*n,d=s*l,p=s*h,_=r*l,f=r*h,g=o*h,m=a*n,v=a*l,b=a*h;return i[0]=1-(_+g),i[1]=d+b,i[2]=p-v,i[3]=0,i[4]=d-b,i[5]=1-(c+g),i[6]=f+m,i[7]=0,i[8]=p+v,i[9]=f-m,i[10]=1-(c+_),i[11]=0,i[12]=t[0],i[13]=t[1],i[14]=t[2],i[15]=1,i},mat4ToEuler(e,t,i=u.vec4()){const s=u.clamp,r=e[0],o=e[4],a=e[8],n=e[1],l=e[5],h=e[9],c=e[2],d=e[6],p=e[10];return"XYZ"===t?(i[1]=Math.asin(s(a,-1,1)),Math.abs(a)<.99999?(i[0]=Math.atan2(-h,p),i[2]=Math.atan2(-o,r)):(i[0]=Math.atan2(d,l),i[2]=0)):"YXZ"===t?(i[0]=Math.asin(-s(h,-1,1)),Math.abs(h)<.99999?(i[1]=Math.atan2(a,p),i[2]=Math.atan2(n,l)):(i[1]=Math.atan2(-c,r),i[2]=0)):"ZXY"===t?(i[0]=Math.asin(s(d,-1,1)),Math.abs(d)<.99999?(i[1]=Math.atan2(-c,p),i[2]=Math.atan2(-o,l)):(i[1]=0,i[2]=Math.atan2(n,r))):"ZYX"===t?(i[1]=Math.asin(-s(c,-1,1)),Math.abs(c)<.99999?(i[0]=Math.atan2(d,p),i[2]=Math.atan2(n,r)):(i[0]=0,i[2]=Math.atan2(-o,l))):"YZX"===t?(i[2]=Math.asin(s(n,-1,1)),Math.abs(n)<.99999?(i[0]=Math.atan2(-h,l),i[1]=Math.atan2(-c,r)):(i[0]=0,i[1]=Math.atan2(a,p))):"XZY"===t&&(i[2]=Math.asin(-s(o,-1,1)),Math.abs(o)<.99999?(i[0]=Math.atan2(d,l),i[1]=Math.atan2(a,r)):(i[0]=Math.atan2(-h,p),i[1]=0)),i},composeMat4:(e,t,i,s=u.mat4())=>(u.quaternionToRotationMat4(t,s),u.scaleMat4v(i,s),u.translateMat4v(e,s),s),decomposeMat4:(()=>{const e=new n(3),t=new n(16);return function(i,s,r,o){e[0]=i[0],e[1]=i[1],e[2]=i[2];let a=u.lenVec3(e);e[0]=i[4],e[1]=i[5],e[2]=i[6];const n=u.lenVec3(e);e[8]=i[8],e[9]=i[9],e[10]=i[10];const l=u.lenVec3(e);u.determinantMat4(i)<0&&(a=-a),s[0]=i[12],s[1]=i[13],s[2]=i[14],t.set(i);const h=1/a,c=1/n,d=1/l;return t[0]*=h,t[1]*=h,t[2]*=h,t[4]*=c,t[5]*=c,t[6]*=c,t[8]*=d,t[9]*=d,t[10]*=d,u.mat4ToQuaternion(t,r),o[0]=a,o[1]=n,o[2]=l,this}})(),getColMat4(e,t){const i=4*t;return[e[i],e[i+1],e[i+2],e[i+3]]},setRowMat4(e,t,i){e[t]=i[0],e[t+4]=i[1],e[t+8]=i[2],e[t+12]=i[3]},lookAtMat4v(e,t,i,s){s||(s=u.mat4());const r=e[0],o=e[1],a=e[2],n=i[0],l=i[1],h=i[2],c=t[0],d=t[1],p=t[2];if(r===c&&o===d&&a===p)return u.identityMat4();let _,f,g,m,v,b,P,y,M,x;return _=r-c,f=o-d,g=a-p,x=1/Math.sqrt(_*_+f*f+g*g),_*=x,f*=x,g*=x,m=l*g-h*f,v=h*_-n*g,b=n*f-l*_,x=Math.sqrt(m*m+v*v+b*b),x?(x=1/x,m*=x,v*=x,b*=x):(m=0,v=0,b=0),P=f*b-g*v,y=g*m-_*b,M=_*v-f*m,x=Math.sqrt(P*P+y*y+M*M),x?(x=1/x,P*=x,y*=x,M*=x):(P=0,y=0,M=0),s[0]=m,s[1]=P,s[2]=_,s[3]=0,s[4]=v,s[5]=y,s[6]=f,s[7]=0,s[8]=b,s[9]=M,s[10]=g,s[11]=0,s[12]=-(m*r+v*o+b*a),s[13]=-(P*r+y*o+M*a),s[14]=-(_*r+f*o+g*a),s[15]=1,s},lookAtMat4c:(e,t,i,s,r,o,a,n,l)=>u.lookAtMat4v([e,t,i],[s,r,o],[a,n,l],[]),orthoMat4c(e,t,i,s,r,o,a){a||(a=u.mat4());const n=t-e,l=s-i,h=o-r;return a[0]=2/n,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2/l,a[6]=0,a[7]=0,a[8]=0,a[9]=0,a[10]=-2/h,a[11]=0,a[12]=-(e+t)/n,a[13]=-(s+i)/l,a[14]=-(o+r)/h,a[15]=1,a},frustumMat4v(e,t,i){i||(i=u.mat4());const s=[e[0],e[1],e[2],0],r=[t[0],t[1],t[2],0];u.addVec4(r,s,l),u.subVec4(r,s,h);const o=2*s[2],a=h[0],n=h[1],c=h[2];return i[0]=o/a,i[1]=0,i[2]=0,i[3]=0,i[4]=0,i[5]=o/n,i[6]=0,i[7]=0,i[8]=l[0]/a,i[9]=l[1]/n,i[10]=-l[2]/c,i[11]=-1,i[12]=0,i[13]=0,i[14]=-o*r[2]/c,i[15]=0,i},frustumMat4(e,t,i,s,r,o,a){a||(a=u.mat4());const n=t-e,l=s-i,h=o-r;return a[0]=2*r/n,a[1]=0,a[2]=0,a[3]=0,a[4]=0,a[5]=2*r/l,a[6]=0,a[7]=0,a[8]=(t+e)/n,a[9]=(s+i)/l,a[10]=-(o+r)/h,a[11]=-1,a[12]=0,a[13]=0,a[14]=-o*r*2/h,a[15]=0,a},perspectiveMat4(e,t,i,s,r){const o=[],a=[];return o[2]=i,a[2]=s,a[1]=o[2]*Math.tan(e/2),o[1]=-a[1],a[0]=a[1]*t,o[0]=-a[0],u.frustumMat4v(o,a,r)},compareMat4:(e,t)=>e[0]===t[0]&&e[1]===t[1]&&e[2]===t[2]&&e[3]===t[3]&&e[4]===t[4]&&e[5]===t[5]&&e[6]===t[6]&&e[7]===t[7]&&e[8]===t[8]&&e[9]===t[9]&&e[10]===t[10]&&e[11]===t[11]&&e[12]===t[12]&&e[13]===t[13]&&e[14]===t[14]&&e[15]===t[15],transformPoint3(e,t,i=u.vec3()){const s=t[0],r=t[1],o=t[2];return i[0]=e[0]*s+e[4]*r+e[8]*o+e[12],i[1]=e[1]*s+e[5]*r+e[9]*o+e[13],i[2]=e[2]*s+e[6]*r+e[10]*o+e[14],i},transformPoint4:(e,t,i=u.vec4())=>(i[0]=e[0]*t[0]+e[4]*t[1]+e[8]*t[2]+e[12]*t[3],i[1]=e[1]*t[0]+e[5]*t[1]+e[9]*t[2]+e[13]*t[3],i[2]=e[2]*t[0]+e[6]*t[1]+e[10]*t[2]+e[14]*t[3],i[3]=e[3]*t[0]+e[7]*t[1]+e[11]*t[2]+e[15]*t[3],i),transformPoints3(e,t,i){const s=i||[],r=t.length;let o,a,n,l;const h=e[0],c=e[1],u=e[2],d=e[3],p=e[4],_=e[5],f=e[6],g=e[7],m=e[8],v=e[9],b=e[10],P=e[11],y=e[12],M=e[13],x=e[14],w=e[15];let E;for(let e=0;e<r;++e)l=t[e],o=l[0],a=l[1],n=l[2],E=s[e]||(s[e]=[0,0,0]),E[0]=h*o+p*a+m*n+y,E[1]=c*o+_*a+v*n+M,E[2]=u*o+f*a+b*n+x,E[3]=d*o+g*a+P*n+w;return s.length=r,s},transformPositions3(e,t,i=t){let s;const r=t.length;let o,a,n;const l=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],_=e[6],f=e[7],g=e[8],m=e[9],v=e[10],b=e[11],P=e[12],y=e[13],M=e[14],x=e[15];for(s=0;s<r;s+=3)o=t[s+0],a=t[s+1],n=t[s+2],i[s+0]=l*o+d*a+g*n+P,i[s+1]=h*o+p*a+m*n+y,i[s+2]=c*o+_*a+v*n+M,i[s+3]=u*o+f*a+b*n+x;return i},transformPositions4(e,t,i=t){let s;const r=t.length;let o,a,n;const l=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],_=e[6],f=e[7],g=e[8],m=e[9],v=e[10],b=e[11],P=e[12],y=e[13],M=e[14],x=e[15];for(s=0;s<r;s+=4)o=t[s+0],a=t[s+1],n=t[s+2],i[s+0]=l*o+d*a+g*n+P,i[s+1]=h*o+p*a+m*n+y,i[s+2]=c*o+_*a+v*n+M,i[s+3]=u*o+f*a+b*n+x;return i},transformVec3(e,t,i){const s=t[0],r=t[1],o=t[2];return(i=i||this.vec3())[0]=e[0]*s+e[4]*r+e[8]*o,i[1]=e[1]*s+e[5]*r+e[9]*o,i[2]=e[2]*s+e[6]*r+e[10]*o,i},transformVec4(e,t,i){const s=t[0],r=t[1],o=t[2],a=t[3];return(i=i||u.vec4())[0]=e[0]*s+e[4]*r+e[8]*o+e[12]*a,i[1]=e[1]*s+e[5]*r+e[9]*o+e[13]*a,i[2]=e[2]*s+e[6]*r+e[10]*o+e[14]*a,i[3]=e[3]*s+e[7]*r+e[11]*o+e[15]*a,i},rotateVec3X(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[0],o[1]=r[1]*Math.cos(i)-r[2]*Math.sin(i),o[2]=r[1]*Math.sin(i)+r[2]*Math.cos(i),s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},rotateVec3Y(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[2]*Math.sin(i)+r[0]*Math.cos(i),o[1]=r[1],o[2]=r[2]*Math.cos(i)-r[0]*Math.sin(i),s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},rotateVec3Z(e,t,i,s){const r=[],o=[];return r[0]=e[0]-t[0],r[1]=e[1]-t[1],r[2]=e[2]-t[2],o[0]=r[0]*Math.cos(i)-r[1]*Math.sin(i),o[1]=r[0]*Math.sin(i)+r[1]*Math.cos(i),o[2]=r[2],s[0]=o[0]+t[0],s[1]=o[1]+t[1],s[2]=o[2]+t[2],s},projectVec4(e,t){const i=1/e[3];return(t=t||u.vec2())[0]=e[0]*i,t[1]=e[1]*i,t},unprojectVec3:(()=>{const e=new n(16),t=new n(16),i=new n(16);return function(s,r,o,a){return this.transformVec3(this.mulMat4(this.inverseMat4(r,e),this.inverseMat4(o,t),i),s,a)}})(),lerpVec3(e,t,i,s,r,o){const a=o||u.vec3(),n=(e-t)/(i-t);return a[0]=s[0]+n*(r[0]-s[0]),a[1]=s[1]+n*(r[1]-s[1]),a[2]=s[2]+n*(r[2]-s[2]),a},lerpMat4(e,t,i,s,r,o){const a=o||u.mat4(),n=(e-t)/(i-t);return a[0]=s[0]+n*(r[0]-s[0]),a[1]=s[1]+n*(r[1]-s[1]),a[2]=s[2]+n*(r[2]-s[2]),a[3]=s[3]+n*(r[3]-s[3]),a[4]=s[4]+n*(r[4]-s[4]),a[5]=s[5]+n*(r[5]-s[5]),a[6]=s[6]+n*(r[6]-s[6]),a[7]=s[7]+n*(r[7]-s[7]),a[8]=s[8]+n*(r[8]-s[8]),a[9]=s[9]+n*(r[9]-s[9]),a[10]=s[10]+n*(r[10]-s[10]),a[11]=s[11]+n*(r[11]-s[11]),a[12]=s[12]+n*(r[12]-s[12]),a[13]=s[13]+n*(r[13]-s[13]),a[14]=s[14]+n*(r[14]-s[14]),a[15]=s[15]+n*(r[15]-s[15]),a},flatten(e){const t=[];let i,s,r,o,a;for(i=0,s=e.length;i<s;i++)for(a=e[i],r=0,o=a.length;r<o;r++)t.push(a[r]);return t},identityQuaternion:(e=u.vec4())=>(e[0]=0,e[1]=0,e[2]=0,e[3]=1,e),eulerToQuaternion(e,t,i=u.vec4()){const s=e[0]*u.DEGTORAD/2,r=e[1]*u.DEGTORAD/2,o=e[2]*u.DEGTORAD/2,a=Math.cos(s),n=Math.cos(r),l=Math.cos(o),h=Math.sin(s),c=Math.sin(r),d=Math.sin(o);return"XYZ"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l-h*c*d):"YXZ"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l+h*c*d):"ZXY"===t?(i[0]=h*n*l-a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l-h*c*d):"ZYX"===t?(i[0]=h*n*l-a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l+h*c*d):"YZX"===t?(i[0]=h*n*l+a*c*d,i[1]=a*c*l+h*n*d,i[2]=a*n*d-h*c*l,i[3]=a*n*l-h*c*d):"XZY"===t&&(i[0]=h*n*l-a*c*d,i[1]=a*c*l-h*n*d,i[2]=a*n*d+h*c*l,i[3]=a*n*l+h*c*d),i},mat4ToQuaternion(e,t=u.vec4()){const i=e[0],s=e[4],r=e[8],o=e[1],a=e[5],n=e[9],l=e[2],h=e[6],c=e[10];let d;const p=i+a+c;return p>0?(d=.5/Math.sqrt(p+1),t[3]=.25/d,t[0]=(h-n)*d,t[1]=(r-l)*d,t[2]=(o-s)*d):i>a&&i>c?(d=2*Math.sqrt(1+i-a-c),t[3]=(h-n)/d,t[0]=.25*d,t[1]=(s+o)/d,t[2]=(r+l)/d):a>c?(d=2*Math.sqrt(1+a-i-c),t[3]=(r-l)/d,t[0]=(s+o)/d,t[1]=.25*d,t[2]=(n+h)/d):(d=2*Math.sqrt(1+c-i-a),t[3]=(o-s)/d,t[0]=(r+l)/d,t[1]=(n+h)/d,t[2]=.25*d),t},vec3PairToQuaternion(e,t,i=u.vec4()){const s=Math.sqrt(u.dotVec3(e,e)*u.dotVec3(t,t));let r=s+u.dotVec3(e,t);return r<1e-8*s?(r=0,Math.abs(e[0])>Math.abs(e[2])?(i[0]=-e[1],i[1]=e[0],i[2]=0):(i[0]=0,i[1]=-e[2],i[2]=e[1])):u.cross3Vec3(e,t,i),i[3]=r,u.normalizeQuaternion(i)},angleAxisToQuaternion(e,t=u.vec4()){const i=e[3]/2,s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t},quaternionToEuler:(()=>{const e=new n(16);return(t,i,s)=>(s=s||u.vec3(),u.quaternionToRotationMat4(t,e),u.mat4ToEuler(e,i,s),s)})(),mulQuaternions(e,t,i=u.vec4()){const s=e[0],r=e[1],o=e[2],a=e[3],n=t[0],l=t[1],h=t[2],c=t[3];return i[0]=a*n+s*c+r*h-o*l,i[1]=a*l+r*c+o*n-s*h,i[2]=a*h+o*c+s*l-r*n,i[3]=a*c-s*n-r*l-o*h,i},vec3ApplyQuaternion(e,t,i=u.vec3()){const s=t[0],r=t[1],o=t[2],a=e[0],n=e[1],l=e[2],h=e[3],c=h*s+n*o-l*r,d=h*r+l*s-a*o,p=h*o+a*r-n*s,_=-a*s-n*r-l*o;return i[0]=c*h+_*-a+d*-l-p*-n,i[1]=d*h+_*-n+p*-a-c*-l,i[2]=p*h+_*-l+c*-n-d*-a,i},quaternionToMat4(e,t){t=u.identityMat4(t);const i=e[0],s=e[1],r=e[2],o=e[3],a=2*i,n=2*s,l=2*r,h=a*o,c=n*o,d=l*o,p=a*i,_=n*i,f=l*i,g=n*s,m=l*s,v=l*r;return t[0]=1-(g+v),t[1]=_+d,t[2]=f-c,t[4]=_-d,t[5]=1-(p+v),t[6]=m+h,t[8]=f+c,t[9]=m-h,t[10]=1-(p+g),t},quaternionToRotationMat4(e,t){const i=e[0],s=e[1],r=e[2],o=e[3],a=i+i,n=s+s,l=r+r,h=i*a,c=i*n,u=i*l,d=s*n,p=s*l,_=r*l,f=o*a,g=o*n,m=o*l;return t[0]=1-(d+_),t[4]=c-m,t[8]=u+g,t[1]=c+m,t[5]=1-(h+_),t[9]=p-f,t[2]=u-g,t[6]=p+f,t[10]=1-(h+d),t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,t},normalizeQuaternion(e,t=e){const i=u.lenVec4([e[0],e[1],e[2],e[3]]);return t[0]=e[0]/i,t[1]=e[1]/i,t[2]=e[2]/i,t[3]=e[3]/i,t},conjugateQuaternion:(e,t=e)=>(t[0]=-e[0],t[1]=-e[1],t[2]=-e[2],t[3]=e[3],t),inverseQuaternion:(e,t)=>u.normalizeQuaternion(u.conjugateQuaternion(e,t)),quaternionToAngleAxis(e,t=u.vec4()){const i=(e=u.normalizeQuaternion(e,c))[3],s=2*Math.acos(i),r=Math.sqrt(1-i*i);return r<.001?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=e[0]/r,t[1]=e[1]/r,t[2]=e[2]/r),t[3]=s,t},AABB3:e=>new n(e||6),AABB2:e=>new n(e||4),OBB3:e=>new n(e||32),OBB2:e=>new n(e||16),Sphere3:(e,t,i,s)=>new n([e,t,i,s]),transformOBB3(e,t,i=t){let s;const r=t.length;let o,a,n;const l=e[0],h=e[1],c=e[2],u=e[3],d=e[4],p=e[5],_=e[6],f=e[7],g=e[8],m=e[9],v=e[10],b=e[11],P=e[12],y=e[13],M=e[14],x=e[15];for(s=0;s<r;s+=4)o=t[s+0],a=t[s+1],n=t[s+2],i[s+0]=l*o+d*a+g*n+P,i[s+1]=h*o+p*a+m*n+y,i[s+2]=c*o+_*a+v*n+M,i[s+3]=u*o+f*a+b*n+x;return i},containsAABB3:function(e,t){return e[0]<=t[0]&&t[3]<=e[3]&&e[1]<=t[1]&&t[4]<=e[4]&&e[2]<=t[2]&&t[5]<=e[5]},getAABB3Diag:(()=>{const e=new n(3),t=new n(3),i=new n(3);return s=>(e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5],u.subVec3(t,e,i),Math.abs(u.lenVec3(i)))})(),getAABB3DiagPoint:(()=>{const e=new n(3),t=new n(3),i=new n(3);return(s,r)=>{e[0]=s[0],e[1]=s[1],e[2]=s[2],t[0]=s[3],t[1]=s[4],t[2]=s[5];const o=u.subVec3(t,e,i),a=r[0]-s[0],n=s[3]-r[0],l=r[1]-s[1],h=s[4]-r[1],c=r[2]-s[2],d=s[5]-r[2];return o[0]+=a>n?a:n,o[1]+=l>h?l:h,o[2]+=c>d?c:d,Math.abs(u.lenVec3(o))}})(),getAABB3Area:e=>(e[3]-e[0])*(e[4]-e[1])*(e[5]-e[2]),getAABB3Center(e,t){const i=t||u.vec3();return i[0]=(e[0]+e[3])/2,i[1]=(e[1]+e[4])/2,i[2]=(e[2]+e[5])/2,i},getAABB2Center(e,t){const i=t||u.vec2();return i[0]=(e[2]+e[0])/2,i[1]=(e[3]+e[1])/2,i},collapseAABB3:(e=u.AABB3())=>(e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MAX_DOUBLE,e[3]=u.MIN_DOUBLE,e[4]=u.MIN_DOUBLE,e[5]=u.MIN_DOUBLE,e),AABB3ToOBB3:(e,t=u.OBB3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=1,t[4]=e[3],t[5]=e[1],t[6]=e[2],t[7]=1,t[8]=e[3],t[9]=e[4],t[10]=e[2],t[11]=1,t[12]=e[0],t[13]=e[4],t[14]=e[2],t[15]=1,t[16]=e[0],t[17]=e[1],t[18]=e[5],t[19]=1,t[20]=e[3],t[21]=e[1],t[22]=e[5],t[23]=1,t[24]=e[3],t[25]=e[4],t[26]=e[5],t[27]=1,t[28]=e[0],t[29]=e[4],t[30]=e[5],t[31]=1,t),positions3ToAABB3:(()=>{const e=new Float32Array(3);return(t,i,s)=>{i=i||u.AABB3();let r,o,a,n=u.MAX_DOUBLE,l=u.MAX_DOUBLE,h=u.MAX_DOUBLE,c=u.MIN_DOUBLE,d=u.MIN_DOUBLE,p=u.MIN_DOUBLE;for(let i=0,_=t.length;i<_;i+=3)s?(e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2],u.decompressPosition(e,s,e),r=e[0],o=e[1],a=e[2]):(r=t[i+0],o=t[i+1],a=t[i+2]),r<n&&(n=r),o<l&&(l=o),a<h&&(h=a),r>c&&(c=r),o>d&&(d=o),a>p&&(p=a);return i[0]=n,i[1]=l,i[2]=h,i[3]=c,i[4]=d,i[5]=p,i}})(),OBB3ToAABB3(e,t=u.AABB3()){let i,s,r,o=u.MAX_DOUBLE,a=u.MAX_DOUBLE,n=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,u=e.length;t<u;t+=4)i=e[t+0],s=e[t+1],r=e[t+2],i<o&&(o=i),s<a&&(a=s),r<n&&(n=r),i>l&&(l=i),s>h&&(h=s),r>c&&(c=r);return t[0]=o,t[1]=a,t[2]=n,t[3]=l,t[4]=h,t[5]=c,t},points3ToAABB3(e,t=u.AABB3()){let i,s,r,o=u.MAX_DOUBLE,a=u.MAX_DOUBLE,n=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE,c=u.MIN_DOUBLE;for(let t=0,u=e.length;t<u;t++)i=e[t][0],s=e[t][1],r=e[t][2],i<o&&(o=i),s<a&&(a=s),r<n&&(n=r),i>l&&(l=i),s>h&&(h=s),r>c&&(c=r);return t[0]=o,t[1]=a,t[2]=n,t[3]=l,t[4]=h,t[5]=c,t},points3ToSphere3:(()=>{const e=new Float32Array(3);return(t,i)=>{i=i||u.vec4();let s,r=0,o=0,a=0;const n=t.length;for(s=0;s<n;s++)r+=t[s][0],o+=t[s][1],a+=t[s][2];i[0]=r/n,i[1]=o/n,i[2]=a/n;let l,h=0;for(s=0;s<n;s++)l=Math.abs(u.lenVec3(u.subVec3(t[s],i,e))),l>h&&(h=l);return i[3]=h,i}})(),positions3ToSphere3:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s)=>{s=s||u.vec4();let r,o=0,a=0,n=0;const l=i.length;let h=0;for(r=0;r<l;r+=3)o+=i[r],a+=i[r+1],n+=i[r+2];const c=l/3;let d;for(s[0]=o/c,s[1]=a/c,s[2]=n/c,r=0;r<l;r+=3)e[0]=i[r],e[1]=i[r+1],e[2]=i[r+2],d=Math.abs(u.lenVec3(u.subVec3(e,s,t))),d>h&&(h=d);return s[3]=h,s}})(),OBB3ToSphere3:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s)=>{s=s||u.vec4();let r,o=0,a=0,n=0;const l=i.length,h=l/4;for(r=0;r<l;r+=4)o+=i[r+0],a+=i[r+1],n+=i[r+2];s[0]=o/h,s[1]=a/h,s[2]=n/h;let c,d=0;for(r=0;r<l;r+=4)e[0]=i[r+0],e[1]=i[r+1],e[2]=i[r+2],c=Math.abs(u.lenVec3(u.subVec3(e,s,t))),c>d&&(d=c);return s[3]=d,s}})(),getSphere3Center:(e,t=u.vec3())=>(t[0]=e[0],t[1]=e[1],t[2]=e[2],t),getPositionsCenter(e,t=u.vec3()){let i=0,s=0,r=0;for(var o=0,a=e.length;o<a;o+=3)i+=e[o+0],s+=e[o+1],r+=e[o+2];const n=e.length/3;return t[0]=i/n,t[1]=s/n,t[2]=r/n,t},expandAABB3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e[4]<t[4]&&(e[4]=t[4]),e[5]<t[5]&&(e[5]=t[5]),e),expandAABB3Point3:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]>t[2]&&(e[2]=t[2]),e[3]<t[0]&&(e[3]=t[0]),e[4]<t[1]&&(e[4]=t[1]),e[5]<t[2]&&(e[5]=t[2]),e),expandAABB3Points3(e,t){for(var i,s,r,o=0,a=t.length;o<a;o+=3)i=t[o],s=t[o+1],r=t[o+2],e[0]>i&&(e[0]=i),e[1]>s&&(e[1]=s),e[2]>r&&(e[2]=r),e[3]<i&&(e[3]=i),e[4]<s&&(e[4]=s),e[5]<r&&(e[5]=r);return e},collapseAABB2:(e=u.AABB2())=>(e[0]=u.MAX_DOUBLE,e[1]=u.MAX_DOUBLE,e[2]=u.MIN_DOUBLE,e[3]=u.MIN_DOUBLE,e),point3AABB3Intersect:(e,t)=>e[0]>t[0]||e[3]<t[0]||e[1]>t[1]||e[4]<t[1]||e[2]>t[2]||e[5]<t[2],planeAABB3Intersect(e,t,i){let s,r;return e[0]>0?(s=e[0]*i[0],r=e[0]*i[3]):(s=e[0]*i[3],r=e[0]*i[0]),e[1]>0?(s+=e[1]*i[1],r+=e[1]*i[4]):(s+=e[1]*i[4],r+=e[1]*i[1]),e[2]>0?(s+=e[2]*i[2],r+=e[2]*i[5]):(s+=e[2]*i[5],r+=e[2]*i[2]),s<=-t&&r<=-t?-1:s>=-t&&r>=-t?1:0},OBB3ToAABB2(e,t=u.AABB2()){let i,s,r,o,a=u.MAX_DOUBLE,n=u.MAX_DOUBLE,l=u.MIN_DOUBLE,h=u.MIN_DOUBLE;for(let t=0,c=e.length;t<c;t+=4)i=e[t+0],s=e[t+1],r=e[t+3]||1,o=1/r,i*=o,s*=o,i<a&&(a=i),s<n&&(n=s),i>l&&(l=i),s>h&&(h=s);return t[0]=a,t[1]=n,t[2]=l,t[3]=h,t},expandAABB2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[2]&&(e[2]=t[2]),e[3]<t[3]&&(e[3]=t[3]),e),expandAABB2Point2:(e,t)=>(e[0]>t[0]&&(e[0]=t[0]),e[1]>t[1]&&(e[1]=t[1]),e[2]<t[0]&&(e[2]=t[0]),e[3]<t[1]&&(e[3]=t[1]),e),AABB2ToCanvas(e,t,i,s=e){const r=.5*(e[0]+1),o=.5*(e[1]+1),a=.5*(e[2]+1),n=.5*(e[3]+1);return s[0]=Math.floor(r*t),s[1]=i-Math.floor(n*i),s[2]=Math.floor(a*t),s[3]=i-Math.floor(o*i),s},tangentQuadraticBezier:(e,t,i,s)=>2*(1-e)*(i-t)+2*e*(s-i),tangentQuadraticBezier3:(e,t,i,s,r)=>-3*t*(1-e)*(1-e)+3*i*(1-e)*(1-e)-6*e*i*(1-e)+6*e*s*(1-e)-3*e*e*s+3*e*e*r,tangentSpline:e=>6*e*e-6*e+(3*e*e-4*e+1)+(-6*e*e+6*e)+(3*e*e-2*e),catmullRomInterpolate(e,t,i,s,r){const o=.5*(i-e),a=.5*(s-t),n=r*r;return(2*t-2*i+o+a)*(r*n)+(-3*t+3*i-2*o-a)*n+o*r+t},b2p0(e,t){const i=1-e;return i*i*t},b2p1:(e,t)=>2*(1-e)*e*t,b2p2:(e,t)=>e*e*t,b2(e,t,i,s){return this.b2p0(e,t)+this.b2p1(e,i)+this.b2p2(e,s)},b3p0(e,t){const i=1-e;return i*i*i*t},b3p1(e,t){const i=1-e;return 3*i*i*e*t},b3p2:(e,t)=>3*(1-e)*e*e*t,b3p3:(e,t)=>e*e*e*t,b3(e,t,i,s,r){return this.b3p0(e,t)+this.b3p1(e,i)+this.b3p2(e,s)+this.b3p3(e,r)},triangleNormal(e,t,i,s=u.vec3()){const r=t[0]-e[0],o=t[1]-e[1],a=t[2]-e[2],n=i[0]-e[0],l=i[1]-e[1],h=i[2]-e[2],c=o*h-a*l,d=a*n-r*h,p=r*l-o*n,_=Math.sqrt(c*c+d*d+p*p);return 0===_?(s[0]=0,s[1]=0,s[2]=0):(s[0]=c/_,s[1]=d/_,s[2]=p/_),s},rayTriangleIntersect:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3);return(o,a,n,l,h,c)=>{c=c||u.vec3();const d=u.subVec3(l,n,e),p=u.subVec3(h,n,t),_=u.cross3Vec3(a,p,i),f=u.dotVec3(d,_);if(f<1e-6)return null;const g=u.subVec3(o,n,s),m=u.dotVec3(g,_);if(m<0||m>f)return null;const v=u.cross3Vec3(g,d,r),b=u.dotVec3(a,v);if(b<0||m+b>f)return null;const P=u.dotVec3(p,v)/f;return c[0]=o[0]+P*a[0],c[1]=o[1]+P*a[1],c[2]=o[2]+P*a[2],c}})(),rayPlaneIntersect:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3);return(r,o,a,n,l,h)=>{h=h||u.vec3(),o=u.normalizeVec3(o,e);const c=u.subVec3(n,a,t),d=u.subVec3(l,a,i),p=u.cross3Vec3(c,d,s);u.normalizeVec3(p,p);const _=-u.dotVec3(a,p),f=-(u.dotVec3(r,p)+_)/u.dotVec3(o,p);return h[0]=r[0]+f*o[0],h[1]=r[1]+f*o[1],h[2]=r[2]+f*o[2],h}})(),cartesianToBarycentric:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3);return(s,r,o,a,n)=>{const l=u.subVec3(a,r,e),h=u.subVec3(o,r,t),c=u.subVec3(s,r,i),d=u.dotVec3(l,l),p=u.dotVec3(l,h),_=u.dotVec3(l,c),f=u.dotVec3(h,h),g=u.dotVec3(h,c),m=d*f-p*p;if(0===m)return null;const v=1/m,b=(f*_-p*g)*v,P=(d*g-p*_)*v;return n[0]=1-b-P,n[1]=P,n[2]=b,n}})(),barycentricInsideTriangle(e){const t=e[1],i=e[2];return i>=0&&t>=0&&i+t<1},barycentricToCartesian(e,t,i,s,r=u.vec3()){const o=e[0],a=e[1],n=e[2];return r[0]=t[0]*o+i[0]*a+s[0]*n,r[1]=t[1]*o+i[1]*a+s[1]*n,r[2]=t[2]*o+i[2]*a+s[2]*n,r},mergeVertices(e,t,i,s){const r={},o=[],a=[],n=t?[]:null,l=i?[]:null,h=[];let c,u,d,p;const _=1e4;let f,g,m=0;for(f=0,g=e.length;f<g;f+=3)c=e[f],u=e[f+1],d=e[f+2],p=`${Math.round(c*_)}_${Math.round(u*_)}_${Math.round(d*_)}`,void 0===r[p]&&(r[p]=a.length/3,a.push(c),a.push(u),a.push(d),t&&(n.push(t[f]),n.push(t[f+1]),n.push(t[f+2])),i&&(l.push(i[m]),l.push(i[m+1]))),o[f/3]=r[p],m+=2;for(f=0,g=s.length;f<g;f++)h[f]=o[s[f]];const v={positions:a,indices:h};return n&&(v.normals=n),l&&(v.uv=l),v},buildNormals:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3),o=new Float32Array(3);return(a,n,l)=>{let h,c;const d=new Array(a.length/3);let p,_,f,g,m,v,b;for(h=0,c=n.length;h<c;h+=3){p=n[h],_=n[h+1],f=n[h+2],e[0]=a[3*p],e[1]=a[3*p+1],e[2]=a[3*p+2],t[0]=a[3*_],t[1]=a[3*_+1],t[2]=a[3*_+2],i[0]=a[3*f],i[1]=a[3*f+1],i[2]=a[3*f+2],u.subVec3(t,e,s),u.subVec3(i,e,r);const l=new Float32Array(3);u.normalizeVec3(u.cross3Vec3(s,r,o),l),d[p]||(d[p]=[]),d[_]||(d[_]=[]),d[f]||(d[f]=[]),d[p].push(l),d[_].push(l),d[f].push(l)}for(l=l&&l.length===a.length?l:new Float32Array(a.length),h=0,c=d.length;h<c;h++){g=d[h].length,m=0,v=0,b=0;for(let e=0;e<g;e++)m+=d[h][e][0],v+=d[h][e][1],b+=d[h][e][2];l[3*h]=m/g,l[3*h+1]=v/g,l[3*h+2]=b/g}return l}})(),buildTangents:(()=>{const e=new Float32Array(3),t=new Float32Array(3),i=new Float32Array(3),s=new Float32Array(3),r=new Float32Array(3),o=new Float32Array(3),a=new Float32Array(3);return(n,l,h)=>{const c=new Float32Array(n.length);for(let d=0;d<l.length;d+=3){let p=l[d];const _=n.subarray(3*p,3*p+3),f=h.subarray(2*p,2*p+2);p=l[d+1];const g=n.subarray(3*p,3*p+3),m=h.subarray(2*p,2*p+2);p=l[d+2];const v=n.subarray(3*p,3*p+3),b=h.subarray(2*p,2*p+2),P=u.subVec3(g,_,e),y=u.subVec3(v,_,t),M=u.subVec2(m,f,i),x=u.subVec2(b,f,s),w=1/(M[0]*x[1]-M[1]*x[0]),E=u.mulVec3Scalar(u.subVec3(u.mulVec3Scalar(P,x[1],r),u.mulVec3Scalar(y,M[1],o),a),w,o);let A;for(let e=0;e<3;e++)A=3*l[d+e],c[A]+=E[0],c[A+1]+=E[1],c[A+2]+=E[2]}return c}})(),buildPickTriangles(e,t,i){const s=t.length,r=i?new Uint16Array(9*s):new Float32Array(9*s),o=new Uint8Array(12*s);let a,n,l,h,c,u,d=0,p=0,_=0;for(let i=0;i<s;i+=3)u=d>>24&255,c=d>>16&255,h=d>>8&255,l=255&d,n=t[i],a=3*n,r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[_++]=l,o[_++]=h,o[_++]=c,o[_++]=u,n=t[i+1],a=3*n,r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[_++]=l,o[_++]=h,o[_++]=c,o[_++]=u,n=t[i+2],a=3*n,r[p++]=e[a],r[p++]=e[a+1],r[p++]=e[a+2],o[_++]=l,o[_++]=h,o[_++]=c,o[_++]=u,d++;return{positions:r,colors:o}},faceToVertexNormals(e,t,i={}){const s=i.smoothNormalsAngleThreshold||20,r={},o=[],a={};let n,l,h,c,d;const p=1e4;let _,f,g,m,v,b;for(f=0,m=e.length;f<m;f+=3){_=f/3,l=e[f],h=e[f+1],c=e[f+2],d=`${Math.round(l*p)}_${Math.round(h*p)}_${Math.round(c*p)}`,void 0===r[d]?r[d]=[_]:r[d].push(_);const i=u.normalizeVec3([t[f],t[f+1],t[f+2]]);o[_]=i,n=u.vec4([i[0],i[1],i[2],1]),a[_]=n}for(d in r)if(r.hasOwnProperty(d)){const e=r[d],t=e.length;for(f=0;f<t;f++){const i=e[f];for(n=a[i],g=0;g<t;g++){if(f===g)continue;const t=e[g];v=o[i],b=o[t],Math.abs(u.angleVec3(v,b)/u.DEGTORAD)<s&&(n[0]+=b[0],n[1]+=b[1],n[2]+=b[2],n[3]+=1)}}}for(f=0,m=t.length;f<m;f+=3)n=a[f/3],t[f+0]=n[0]/n[3],t[f+1]=n[1]/n[3],t[f+2]=n[2]/n[3]},canvasPosToWorldRay:(()=>{const e=new Float32Array(16),t=new Float32Array(16),i=new Float32Array(4),s=new Float32Array(4),r=new Float32Array(4),o=new Float32Array(4);return(a,n,l,h,c,d)=>{const p=u.mulMat4(l,n,e),_=u.inverseMat4(p,t),f=a.width,g=a.height,m=(h[0]-f/2)/(f/2),v=-(h[1]-g/2)/(g/2);i[0]=m,i[1]=v,i[2]=-1,i[3]=1,u.transformVec4(_,i,s),u.mulVec4Scalar(s,1/s[3]),r[0]=m,r[1]=v,r[2]=1,r[3]=1,u.transformVec4(_,r,o),u.mulVec4Scalar(o,1/o[3]),c[0]=o[0],c[1]=o[1],c[2]=o[2],u.subVec3(o,s,d),u.normalizeVec3(d)}})(),canvasPosToLocalRay:(()=>{const e=new Float32Array(3),t=new Float32Array(3);return(i,s,r,o,a,n,l)=>{u.canvasPosToWorldRay(i,s,r,a,e,t),u.worldRayToLocalRay(o,e,t,n,l)}})(),worldRayToLocalRay:(()=>{const e=new Float32Array(16),t=new Float32Array(4),i=new Float32Array(4);return(s,r,o,a,n)=>{const l=u.inverseMat4(s,e);t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,u.transformVec4(l,t,i),a[0]=i[0],a[1]=i[1],a[2]=i[2],u.transformVec3(l,o,n)}})(),buildKDTree:(()=>{const e=new Float32Array;function t(i,s,r,o){const a=new Float32Array(6),n={triangles:null,left:null,right:null,leaf:!1,splitDim:0,aabb:a};let l,h;for(a[0]=a[1]=a[2]=Number.POSITIVE_INFINITY,a[3]=a[4]=a[5]=Number.NEGATIVE_INFINITY,l=0,h=i.length;l<h;++l){var c=3*i[l];for(let e=0;e<3;++e){const t=3*s[c+e];r[t]<a[0]&&(a[0]=r[t]),r[t]>a[3]&&(a[3]=r[t]),r[t+1]<a[1]&&(a[1]=r[t+1]),r[t+1]>a[4]&&(a[4]=r[t+1]),r[t+2]<a[2]&&(a[2]=r[t+2]),r[t+2]>a[5]&&(a[5]=r[t+2])}}if(i.length<20||o>10)return n.triangles=i,n.leaf=!0,n;e[0]=a[3]-a[0],e[1]=a[4]-a[1],e[2]=a[5]-a[2];let u=0;e[1]>e[u]&&(u=1),e[2]>e[u]&&(u=2),n.splitDim=u;const d=(a[u]+a[u+3])/2,p=new Array(i.length);let _=0;const f=new Array(i.length);let g=0;for(l=0,h=i.length;l<h;++l){const e=s[c=3*i[l]],t=3*s[c+1],o=3*s[c+2];r[3*e+u]<=d||r[t+u]<=d||r[o+u]<=d?p[_++]=i[l]:f[g++]=i[l]}return p.length=_,f.length=g,n.left=t(p,s,r,o+1),n.right=t(f,s,r,o+1),n}return(e,i)=>{const s=e.length/3,r=new Array(s);for(let e=0;e<s;++e)r[e]=e;return t(r,e,i,0)}})(),decompressPosition(e,t,i){i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14]},decompressPositions(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressUV(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},decompressUVs(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},octDecodeVec2(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t},octDecodeVec2s(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],o=e[i+1];r=(2*r+1)/255,o=(2*o+1)/255;const a=1-Math.abs(r)-Math.abs(o);a<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const n=Math.sqrt(r*r+o*o+a*a);t[s+0]=r/n,t[s+1]=o/n,t[s+2]=a/n,s+=3}return t}};u.buildEdgeIndices=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const a=new Uint16Array(3),n=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),d=u.vec3(),p=u.vec3(),_=u.vec3(),f=u.vec3(),g=u.vec3();return function(m,v,b,P){!function(r,o){const a={};let n,l,h,c;const u=Math.pow(10,4);let d,p,_=0;for(d=0,p=r.length;d<p;d+=3)n=r[d],l=r[d+1],h=r[d+2],c=Math.round(n*u)+"_"+Math.round(l*u)+"_"+Math.round(h*u),void 0===a[c]&&(a[c]=_/3,e[_++]=n,e[_++]=l,e[_++]=h),t[d/3]=a[c];for(d=0,p=o.length;d<p;d++)s[d]=t[o[d]],i[s[d]]=o[d]}(m,v),function(t,i){o=0;for(let m=0,v=t;m<v;m+=3){const t=3*s[m],v=3*s[m+1],b=3*s[m+2];i?(a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],n[0]=e[v],n[1]=e[v+1],n[2]=e[v+2],l[0]=e[b],l[1]=e[b+1],l[2]=e[b+2],u.decompressPosition(a,i,h),u.decompressPosition(n,i,c),u.decompressPosition(l,i,d)):(h[0]=e[t],h[1]=e[t+1],h[2]=e[t+2],c[0]=e[v],c[1]=e[v+1],c[2]=e[v+2],d[0]=e[b],d[1]=e[b+1],d[2]=e[b+2]),u.subVec3(d,c,p),u.subVec3(h,c,_),u.cross3Vec3(p,_,f),u.normalizeVec3(f,g);const P=r[o]||(r[o]={normal:u.vec3()});P.normal[0]=g[0],P.normal[1]=g[1],P.normal[2]=g[2],o++}}(v.length,b);const y=[],M=Math.cos(u.DEGTORAD*P),x={};let w,E,A,C,S,D,L,B,T,R,F,N=!1;for(let e=0,t=v.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)w=s[e+i],E=s[e+(i+1)%3],A=Math.min(w,E),C=Math.max(w,E),S=A+","+C,void 0===x[S]?x[S]={index1:A,index2:C,face1:t,face2:void 0}:x[S].face2=t}for(S in x)D=x[S],void 0!==D.face2&&(L=r[D.face1].normal,B=r[D.face2].normal,T=u.dotVec3(L,B),T>M)||(R=i[D.index1],F=i[D.index2],(!N&&R>65535||F>65535)&&(N=!0),y.push(R),y.push(F));return N?new Uint32Array(y):new Uint16Array(y)}}();const d={build:{version:"0.8"},client:{browser:navigator&&navigator.userAgent?navigator.userAgent:"n/a"},components:{scenes:0,models:0,meshes:0,objects:0},memory:{meshes:0,positions:0,colors:0,normals:0,uvs:0,indices:0,textures:0,transforms:0,materials:0,programs:0},frame:{frameCount:0,fps:0,useProgram:0,bindTexture:0,bindArray:0,drawElements:0,drawArrays:0,tasksRun:0,tasksScheduled:0}};var p=[["0",10],["A",26],["a",26],["_",1],["$",1]].map((function(e){for(var t=[],i=e[0].charCodeAt(0),s=i+e[1],r=i;r<s;++r)t.push(r);return String.fromCharCode.apply(null,t)})).join("");function _(e,t){return(t&&4!==t?[0,6]:[0,6,12,18]).map((function(t){return p.substr(parseInt(e/(1<<t))%64,1)})).reverse().join("")}const f={xmlToJson:function e(t,i){if(t.nodeType===t.TEXT_NODE){var s=t.nodeValue;if(null===s.match(/^\s+$/))return s}else if(t.nodeType===t.ELEMENT_NODE||t.nodeType===t.DOCUMENT_NODE){var r={type:t.nodeName,children:[]};if(t.nodeType===t.ELEMENT_NODE)for(var o=0;o<t.attributes.length;o++){var a=t.attributes[o];r[i[a.nodeName]||a.nodeName]=a.nodeValue}for(var n=0;n<t.childNodes.length;n++)(o=e(t.childNodes[n],i))&&r.children.push(o);return r}},clone:function(e){return JSON.parse(JSON.stringify(e))},compressGuid:function(e){var t=[0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30].map((function(t){return parseInt(e.substr(t,2),16)}));return _(t[0],2)+[1,4,7,10,13].map((function(e){return _((t[e]<<16)+(t[e+1]<<8)+t[e+2])})).join("")},findNodeOfType:function(e,t){var i=[],s=function(e){e.type===t&&i.push(e),(e.children||[]).forEach((function(e){s(e)}))};return s(e),i},timeout:function(e){return new Promise((function(t,i){setTimeout(t,e)}))},httpRequest:function(e){return new Promise((function(t,i){var s=new XMLHttpRequest;s.open(e.method||"GET",e.url,!0),s.onload=function(r){console.log(e.url,s.readyState,s.status),4===s.readyState&&(200===s.status?t(s.responseXML):i(s.statusText))},s.send(null)}))},loadJSON:function(e,t,i){var s=e=>{};t=t||s,i=i||s;var r=new XMLHttpRequest;r.overrideMimeType("application/json"),r.open("GET",e,!0),r.addEventListener("load",(function(e){var s=e.target.response;if(200===this.status){var r;try{r=JSON.parse(s)}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}t(r)}else if(0===this.status){console.warn("loadFile: HTTP Status 0 received.");try{t(JSON.parse(s))}catch(e){i(`utils.loadJSON(): Failed to parse JSON response - ${e}`)}}else i(e)}),!1),r.addEventListener("error",(function(e){i(e)}),!1),r.send(null)},loadArraybuffer:function(e,t,i){var s=e=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const s=!!r[2];var o=r[3];o=window.decodeURIComponent(o),s&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var a=0;a<o.length;a++)i[a]=o.charCodeAt(a);window.setTimeout((function(){t(e)}),0)}catch(e){window.setTimeout((function(){i(e)}),0)}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("loadArrayBuffer error : "+s.response))},s.send(null)}},queryString:function(){for(var e={},t=window.location.search.substring(1).split("&"),i=0;i<t.length;i++){var s=t[i].split("=");if(void 0===e[s[0]])e[s[0]]=decodeURIComponent(s[1]);else if("string"==typeof e[s[0]]){var r=[e[s[0]],decodeURIComponent(s[1])];e[s[0]]=r}else e[s[0]].push(decodeURIComponent(s[1]))}return e}(),isArray:function(e){return e&&!e.propertyIsEnumerable("length")&&"object"==typeof e&&"number"==typeof e.length},isString:function(e){return"string"==typeof e||e instanceof String},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},isID:function(e){return f.isString(e)||f.isNumeric(e)},isSameComponent:function(e,t){return!(!e||!t)&&(f.isNumeric(e)||f.isString(e)?`${e}`:e.id)===(f.isNumeric(t)||f.isString(t)?`${t}`:t.id)},isFunction:function(e){return"function"==typeof e},isObject:function(e){const t={}.constructor;return!!e&&e.constructor===t},copy:function(e){return f.apply(e,{})},apply:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(t[i]=e[i]);return t},apply2:function(e,t){for(const i in e)e.hasOwnProperty(i)&&void 0!==e[i]&&null!==e[i]&&(t[i]=e[i]);return t},applyIf:function(e,t){for(const i in e)e.hasOwnProperty(i)&&(void 0!==t[i]&&null!==t[i]||(t[i]=e[i]));return t},isEmptyObject:function(e){for(const t in e)if(e.hasOwnProperty(t))return!1;return!0},inQuotes:function(e){return f.isNumeric(e)?`${e}`:`'${e}'`},concat:function(e,t){const i=new e.constructor(e.length+t.length);return i.set(e),i.set(t,e.length),i},flattenParentChildHierarchy:function(e){var t=[];return function e(i){i.id=i.uuid,delete i.oid,t.push(i);var s=i.children;if(s)for(var r=0,o=s.length;r<o;r++)s[r].parent=i.id,e(s[r]);i.children=[]}(e),t}},g={},m=new e,v=new class{constructor(){this._head=[],this._headLength=0,this._tail=[],this._index=0,this._length=0}get length(){return this._length}shift(){if(this._index>=this._headLength){const e=this._head;if(e.length=0,this._head=this._tail,this._tail=e,this._index=0,this._headLength=this._head.length,!this._headLength)return}const e=this._head[this._index];return this._index<0?delete this._head[this._index++]:this._head[this._index++]=void 0,this._length--,e}push(e){return this._length++,this._tail.push(e),this}unshift(e){return this._head[--this._index]=e,this._length++,this}},b={sceneId:null,time:null,startTime:null,prevTime:null,deltaTime:null},P=[];let y,M=0,x=0;const w=new function(){this.version="1.0.0",this.scenes={},this._superTypes={},this._addScene=function(e){if(e.id){if(w.scenes[e.id])return void console.error(`[ERROR] Scene ${f.inQuotes(e.id)} already exists`)}else e.id=m.addItem({});w.scenes[e.id]=e;const t=e.ticksPerOcclusionTest,i=e.ticksPerRender;g[e.id]={ticksPerOcclusionTest:t,ticksPerRender:i,renderCountdown:i},d.components.scenes++,e.once("destroyed",(()=>{m.removeItem(e.id),delete w.scenes[e.id],delete g[e.id],d.components.scenes--}))},this.clear=function(){let e;for(const t in w.scenes)w.scenes.hasOwnProperty(t)&&(e=w.scenes[t],"default.scene"===t?e.clear():(e.destroy(),delete w.scenes[e.id]))},this.scheduleTask=function(e,t){v.push(e),v.push(t)},this.runTasks=function(e=-1){let t,i,s=(new Date).getTime(),r=0;for(;v.length>0&&(e<0||s<e);)t=v.shift(),i=v.shift(),i?t.call(i):t(),s=(new Date).getTime(),r++;return r},this.getNumTasks=function(){return v.length}},E=function(){let e=Date.now();if(M>0){y=e-M;var t=1e3/y;x+=t,P.push(t),P.length>=30&&(x-=P.shift()),d.frame.fps=Math.round(x/P.length)}!function(e){const t=w.runTasks(e+10),i=w.getNumTasks();d.frame.tasksRun=t,d.frame.tasksScheduled=i,d.frame.tasksBudget=10}(e),function(e){for(var t in b.time=e,w.scenes)if(w.scenes.hasOwnProperty(t)){var i=w.scenes[t];b.sceneId=t,b.startTime=i.startTime,b.deltaTime=null!=b.prevTime?b.time-b.prevTime:0,i.fire("tick",b,!0)}b.prevTime=e}(e),function(){const e=w.scenes;let t,i,s,r,o;for(o in e)e.hasOwnProperty(o)&&(t=e[o],i=g[o],i||(i=g[o]={}),s=t.ticksPerOcclusionTest,i.ticksPerOcclusionTest!==s&&(i.ticksPerOcclusionTest=s,i.renderCountdown=s),--t.occlusionTestCountdown<=0&&(t.doOcclusionTest(),t.occlusionTestCountdown=s),r=t.ticksPerRender,i.ticksPerRender!==r&&(i.ticksPerRender=r,i.renderCountdown=r),0==--i.renderCountdown&&(t.render(false),i.renderCountdown=r))}(),M=e,window.requestAnimationFrame(E)};window.requestAnimationFrame(E);class A{get type(){return"Component"}get isComponent(){return!0}constructor(e=null,t={}){if(this.scene=null,"Scene"===this.type)this.scene=this,this.viewer=t.viewer;else{if("Scene"===e.type)this.scene=e;else{if(!(e instanceof A))throw"Invalid param: owner must be a Component";this.scene=e.scene}this._owner=e,this._renderer=this.scene._renderer}this._dontClear=!!t.dontClear,this._renderer=this.scene._renderer,this.meta=t.meta||{},this.id=t.id,this.destroyed=!1,this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._eventSubsNum=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this!==this.scene&&this.scene._addComponent(this),this._updateScheduled=!1,e&&e._own(this)}glRedraw(){this._renderer&&(this._renderer.imageDirty(),this.castsShadow&&this._renderer.shadowsDirty())}glResort(){this._renderer&&this._renderer.needStateSort()}get owner(){return this._owner}isType(e){return this.type===e}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={},this._eventSubsNum={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(t,i,s){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new e),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={}),this._eventSubsNum||(this._eventSubsNum={});let r=this._eventSubs[t];r?this._eventSubsNum[t]++:(r={},this._eventSubs[t]=r,this._eventSubsNum[t]=1);const o=this._subIdMap.addItem();r[o]={callback:i,scope:s||this},this._subIdEvents[o]=t;const a=this._events[t];return void 0!==a&&i.call(s||this,a),o}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&(delete i[e],this._eventSubsNum[t]--),this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}hasSubs(e){return this._eventSubsNum&&this._eventSubsNum[e]>0}log(e){e="[LOG]"+this._message(e),window.console.log(e),this.scene.fire("log",e)}_message(e){return" ["+this.type+" "+f.inQuotes(this.id)+"]: "+e}warn(e){e="[WARN]"+this._message(e),window.console.warn(e),this.scene.fire("warn",e)}error(e){e="[ERROR]"+this._message(e),window.console.error(e),this.scene.fire("error",e)}_attach(e){const t=e.name;if(!t)return void this.error("Component 'name' expected");let i=e.component;const s=e.sceneDefault,r=e.sceneSingleton,o=e.type,a=e.on,n=!1!==e.recompiles;if(i&&(f.isNumeric(i)||f.isString(i))){const e=i;if(i=this.scene.components[e],!i)return void this.error("Component not found: "+f.inQuotes(e))}if(!i)if(!0===r){const e=this.scene.types[o];for(const t in e)if(e.hasOwnProperty){i=e[t];break}if(!i)return this.error("Scene has no default component for '"+t+"'"),null}else if(!0===s&&(i=this.scene[t],!i))return this.error("Scene has no default component for '"+t+"'"),null;if(i){if(i.scene.id!==this.scene.id)return void this.error("Not in same scene: "+i.type+" "+f.inQuotes(i.id));if(o&&!i.isType(o))return void this.error("Expected a "+o+" type or subtype: "+i.type+" "+f.inQuotes(i.id))}this._attachments||(this._attachments={});const l=this._attached[t];let h,c,u;if(l){if(i&&l.id===i.id)return;const e=this._attachments[l.id];for(h=e.subs,c=0,u=h.length;c<u;c++)l.off(h[c]);delete this._attached[t],delete this._attachments[l.id];const s=e.params.onDetached;s&&(f.isFunction(s)?s(l):s.scope?s.callback.call(s.scope,l):s.callback(l)),e.managingLifecycle&&l.destroy()}if(i){const s={params:e,component:i,subs:[],managingLifecycle:!1};s.subs.push(i.once("destroyed",(function(){s.params.component=null,this._attach(s.params)}),this)),n&&s.subs.push(i.on("dirty",(function(){this.fire("dirty",this)}),this)),this._attached[t]=i,this._attachments[i.id]=s;const r=e.onAttached;if(r&&(f.isFunction(r)?r(i):r.scope?r.callback.call(r.scope,i):r.callback(i)),a){let e,t,r,o;for(e in a)if(a.hasOwnProperty(e)){if(t=a[e],f.isFunction(t)?(r=t,o=null):(r=t.callback,o=t.scope),!r)continue;s.subs.push(i.on(e,r,o))}}}return n&&this.fire("dirty",this),this.fire(t,i),i}_checkComponent(e,t){if(!t.isComponent){if(!f.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(e===t.type){if(t.scene.id===this.scene.id)return t;this.error("Not in same scene: "+t.type)}else this.error("Expected a "+e+" Component")}_checkComponent2(e,t){if(!t.isComponent){if(!f.isID(t))return void this.error("Expected a Component or ID");{const e=t;if(!(t=this.scene.components[e]))return void this.error("Component not found: "+e)}}if(t.scene.id===this.scene.id){for(var i=0,s=e.length;i<s;i++)if(e[i]===t.type)return t;return this.error("Expected component types: "+e),null}this.error("Not in same scene: "+t.type)}_own(e){this._ownedComponents||(this._ownedComponents={}),this._ownedComponents[e.id]||(this._ownedComponents[e.id]=e),e.once("destroyed",(()=>{delete this._ownedComponents[e.id]}),this)}_needUpdate(e){this._updateScheduled||(this._updateScheduled=!0,0===e?this._doUpdate():w.scheduleTask(this._doUpdate,this))}_doUpdate(){this._updateScheduled&&(this._updateScheduled=!1,this._update&&this._update())}_update(){}clear(){if(this._ownedComponents)for(var e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(this._ownedComponents[e].destroy(),delete this._ownedComponents[e])}destroy(){if(this.destroyed)return;let e,t,i,s,r,o;if(this.fire("destroyed",this.destroyed=!0),this._attachments)for(e in this._attachments)if(this._attachments.hasOwnProperty(e)){for(t=this._attachments[e],i=t.component,s=t.subs,r=0,o=s.length;r<o;r++)i.off(s[r]);t.managingLifecycle&&i.destroy()}if(this._ownedComponents)for(e in this._ownedComponents)this._ownedComponents.hasOwnProperty(e)&&(i=this._ownedComponents[e],i.destroy(),delete this._ownedComponents[e]);this.scene._removeComponent(this),this._attached={},this._attachments=null,this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._ownedComponents=null,this._updateScheduled=!1}}const C=16,S=256,D=512,L=1024,B=2048,T=new Float32Array([0,0,0]),R=new Uint16Array([0,0,0]);class F{constructor(e,t,i,s,r,o){this._isObject=t,this.scene=e.scene,this.model=e,this.meshes=s,this._numTriangles=0;for(var a=0,n=this.meshes.length;a<n;a++){const e=this.meshes[a];e.parent=this,this._numTriangles+=e.numTriangles}this.id=i,this.originalSystemId=u.unglobalizeObjectId(e.id,i),this._flags=r,this._aabb=o,this._offsetAABB=u.AABB3(o),this._offset=u.vec3(),this._isObject&&e.scene._registerObject(this)}get isEntity(){return!0}get isModel(){return!1}get isObject(){return this._isObject}get aabb(){return this._offsetAABB}get numTriangles(){return this._numTriangles}set visible(e){if(!!(1&this._flags)!==e){this._flags=e?1|this._flags:-2&this._flags;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setVisible(this._flags);this._isObject&&this.model.scene._objectVisibilityUpdated(this),this.model.glRedraw()}}get visible(){return this._getFlag(1)}_getFlag(e){return!!(this._flags&e)}set highlighted(e){if(!!(this._flags&D)!==e){this._flags=e?this._flags|D:this._flags&~D;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setHighlighted(this._flags);this._isObject&&this.model.scene._objectHighlightedUpdated(this),this.model.glRedraw()}}get highlighted(){return this._getFlag(D)}set xrayed(e){if(!!(this._flags&S)!==e){this._flags=e?this._flags|S:this._flags&~S;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setXRayed(this._flags);this._isObject&&this.model.scene._objectXRayedUpdated(this),this.model.glRedraw()}}get xrayed(){return this._getFlag(S)}set selected(e){if(!!(this._flags&L)!==e){this._flags=e?this._flags|L:this._flags&~L;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setSelected(this._flags);this._isObject&&this.model.scene._objectSelectedUpdated(this),this.model.glRedraw()}}get selected(){return this._getFlag(L)}set edges(e){if(!!(this._flags&B)!==e){this._flags=e?this._flags|B:this._flags&~B;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setEdges(this._flags);this.model.glRedraw()}}get edges(){return this._getFlag(B)}set culled(e){if(!!(4&this._flags)!==e){this._flags=e?4|this._flags:-5&this._flags;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCulled(this._flags);this.model.glRedraw()}}get culled(){return this._getFlag(4)}set clippable(e){if(!!(this._flags&C)!==e){this._flags=e?this._flags|C:this._flags&~C;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setClippable(this._flags);this.model.glRedraw()}}get clippable(){return this._getFlag(C)}set collidable(e){if(!!(32&this._flags)!==e){this._flags=e?32|this._flags:-33&this._flags;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setCollidable(this._flags)}}get collidable(){return this._getFlag(32)}set pickable(e){if(!!(8&this._flags)!==e){this._flags=e?8|this._flags:-9&this._flags;for(var t=0,i=this.meshes.length;t<i;t++)this.meshes[t]._setPickable(this._flags)}}get pickable(){return this._getFlag(8)}set colorize(e){if(e){R[0]=Math.floor(255*e[0]),R[1]=Math.floor(255*e[1]),R[2]=Math.floor(255*e[2]);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(R)}else for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setColorize(null);if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}this.model.glRedraw()}get colorize(){if(0===this.meshes.length)return null;const e=this.meshes[0]._colorize;return T[0]=e[0]/255,T[1]=e[1]/255,T[2]=e[2]/255,T}set opacity(e){if(0===this.meshes.length)return;const t=null!=e,i=this.meshes[0]._colorize[3];let s=255;if(t){if(e<0?e=0:e>1&&(e=1),s=Math.floor(255*e),i===s)return}else if(s=255,i===s)return;for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOpacity(s,this._flags);this._isObject&&this.scene._objectOpacityUpdated(this,t),this.model.glRedraw()}get opacity(){return this.meshes.length>0?this.meshes[0]._colorize[3]/255:1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._setOffset(this._offset);this._offsetAABB[0]=this._aabb[0]+this._offset[0],this._offsetAABB[1]=this._aabb[1]+this._offset[1],this._offsetAABB[2]=this._aabb[2]+this._offset[2],this._offsetAABB[3]=this._aabb[3]+this._offset[0],this._offsetAABB[4]=this._aabb[4]+this._offset[1],this._offsetAABB[5]=this._aabb[5]+this._offset[2],this.scene._aabbDirty=!0,this.scene._objectOffsetUpdated(this,e),this.model._aabbDirty=!0,this.model.glRedraw()}get offset(){return this._offset}set castsShadow(e){}get castsShadow(){return!1}set receivesShadow(e){}get receivesShadow(){return!1}get saoEnabled(){return this.model.saoEnabled}_finalize(){const e=this.model.scene;this._isObject&&(this.visible&&e._objectVisibilityUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._finalize(this._flags)}_destroy(){const e=this.model.scene;this._isObject&&(e._deregisterObject(this),this.visible&&e._objectVisibilityUpdated(this,!1),this.xrayed&&e._objectXRayedUpdated(this),this.selected&&e._objectSelectedUpdated(this),this.highlighted&&e._objectHighlightedUpdated(this),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.scene._objectOffsetUpdated(this,!1));for(let e=0,t=this.meshes.length;e<t;e++)this.meshes[e]._destroy();e._aabbDirty=!0}}const N=u.vec3();u.AABB3();const I=function(){const e=new Float32Array(16),t=new Float64Array(4),i=new Float64Array(4);return function(s,r,o=e){return t[0]=r[0],t[1]=r[1],t[2]=r[2],t[3]=1,u.transformVec4(s,t,i),u.setMat4Translation(s,i,o),o}}();function O(e,t,i,s){const r=u.dotVec3(t,i)+e,o=u.normalizeVec3(t,N);return u.mulVec3Scalar(o,-r,s),s}u.vec4(),u.vec4();u.vec3(),u.vec3();u.vec3(),u.vec3(),u.vec3();class k extends A{get type(){return"Spinner"}constructor(e,t={}){super(e,t),this._canvas=t.canvas,this._element=null,this._isCustom=!1,t.elementId&&(this._element=document.getElementById(t.elementId),this._element?this._adjustPosition():this.error("Can't find given Spinner HTML element: '"+t.elementId+"' - will automatically create default element")),this._element||this._createDefaultSpinner(),this.processes=0}_createDefaultSpinner(){this._injectDefaultCSS();const e=document.createElement("div"),t=e.style;t["z-index"]="9000",t.position="absolute",e.innerHTML='<div class="sk-fading-circle">                <div class="sk-circle1 sk-circle"></div>                <div class="sk-circle2 sk-circle"></div>                <div class="sk-circle3 sk-circle"></div>                <div class="sk-circle4 sk-circle"></div>                <div class="sk-circle5 sk-circle"></div>                <div class="sk-circle6 sk-circle"></div>                <div class="sk-circle7 sk-circle"></div>                <div class="sk-circle8 sk-circle"></div>                <div class="sk-circle9 sk-circle"></div>                <div class="sk-circle10 sk-circle"></div>                <div class="sk-circle11 sk-circle"></div>                <div class="sk-circle12 sk-circle"></div>                </div>',this._canvas.parentElement.appendChild(e),this._element=e,this._isCustom=!1,this._adjustPosition()}_injectDefaultCSS(){const e="xeokit-spinner-css";if(document.getElementById(e))return;const t=document.createElement("style");t.innerHTML=".sk-fading-circle {        background: transparent;        margin: 20px auto;        width: 50px;        height:50px;        position: relative;        }        .sk-fading-circle .sk-circle {        width: 120%;        height: 120%;        position: absolute;        left: 0;        top: 0;        }        .sk-fading-circle .sk-circle:before {        content: '';        display: block;        margin: 0 auto;        width: 15%;        height: 15%;        background-color: #ff8800;        border-radius: 100%;        -webkit-animation: sk-circleFadeDelay 1.2s infinite ease-in-out both;        animation: sk-circleFadeDelay 1.2s infinite ease-in-out both;        }        .sk-fading-circle .sk-circle2 {        -webkit-transform: rotate(30deg);        -ms-transform: rotate(30deg);        transform: rotate(30deg);    }    .sk-fading-circle .sk-circle3 {        -webkit-transform: rotate(60deg);        -ms-transform: rotate(60deg);        transform: rotate(60deg);    }    .sk-fading-circle .sk-circle4 {        -webkit-transform: rotate(90deg);        -ms-transform: rotate(90deg);        transform: rotate(90deg);    }    .sk-fading-circle .sk-circle5 {        -webkit-transform: rotate(120deg);        -ms-transform: rotate(120deg);        transform: rotate(120deg);    }    .sk-fading-circle .sk-circle6 {        -webkit-transform: rotate(150deg);        -ms-transform: rotate(150deg);        transform: rotate(150deg);    }    .sk-fading-circle .sk-circle7 {        -webkit-transform: rotate(180deg);        -ms-transform: rotate(180deg);        transform: rotate(180deg);    }    .sk-fading-circle .sk-circle8 {        -webkit-transform: rotate(210deg);        -ms-transform: rotate(210deg);        transform: rotate(210deg);    }    .sk-fading-circle .sk-circle9 {        -webkit-transform: rotate(240deg);        -ms-transform: rotate(240deg);        transform: rotate(240deg);    }    .sk-fading-circle .sk-circle10 {        -webkit-transform: rotate(270deg);        -ms-transform: rotate(270deg);        transform: rotate(270deg);    }    .sk-fading-circle .sk-circle11 {        -webkit-transform: rotate(300deg);        -ms-transform: rotate(300deg);        transform: rotate(300deg);    }    .sk-fading-circle .sk-circle12 {        -webkit-transform: rotate(330deg);        -ms-transform: rotate(330deg);        transform: rotate(330deg);    }    .sk-fading-circle .sk-circle2:before {        -webkit-animation-delay: -1.1s;        animation-delay: -1.1s;    }    .sk-fading-circle .sk-circle3:before {        -webkit-animation-delay: -1s;        animation-delay: -1s;    }    .sk-fading-circle .sk-circle4:before {        -webkit-animation-delay: -0.9s;        animation-delay: -0.9s;    }    .sk-fading-circle .sk-circle5:before {        -webkit-animation-delay: -0.8s;        animation-delay: -0.8s;    }    .sk-fading-circle .sk-circle6:before {        -webkit-animation-delay: -0.7s;        animation-delay: -0.7s;    }    .sk-fading-circle .sk-circle7:before {        -webkit-animation-delay: -0.6s;        animation-delay: -0.6s;    }    .sk-fading-circle .sk-circle8:before {        -webkit-animation-delay: -0.5s;        animation-delay: -0.5s;    }    .sk-fading-circle .sk-circle9:before {        -webkit-animation-delay: -0.4s;        animation-delay: -0.4s;    }    .sk-fading-circle .sk-circle10:before {        -webkit-animation-delay: -0.3s;        animation-delay: -0.3s;    }    .sk-fading-circle .sk-circle11:before {        -webkit-animation-delay: -0.2s;        animation-delay: -0.2s;    }    .sk-fading-circle .sk-circle12:before {        -webkit-animation-delay: -0.1s;        animation-delay: -0.1s;    }    @-webkit-keyframes sk-circleFadeDelay {        0%, 39%, 100% { opacity: 0; }        40% { opacity: 1; }    }    @keyframes sk-circleFadeDelay {        0%, 39%, 100% { opacity: 0; }        40% { opacity: 1; }    }",t.id=e,document.body.appendChild(t)}_adjustPosition(){if(this._isCustom)return;const e=this._canvas,t=this._element,i=t.style;i.left=e.offsetLeft+.5*e.clientWidth-.5*t.clientWidth+"px",i.top=e.offsetTop+.5*e.clientHeight-.5*t.clientHeight+"px"}set processes(e){if(e=e||0,this._processes===e)return;if(e<0)return;const t=this._processes;this._processes=e;const i=this._element;i&&(i.style.visibility=this._processes>0?"visible":"hidden"),this.fire("processes",this._processes),0===this._processes&&this._processes!==t&&this.fire("zeroProcesses",this._processes)}get processes(){return this._processes}_destroy(){this._element&&!this._isCustom&&(this._element.parentNode.removeChild(this._element),this._element=null)}}const V={WEBGL:!1,SUPPORTED_EXTENSIONS:{}},j=document.createElement("canvas");if(j){const e=j.getContext("webgl",{antialias:!0})||j.getContext("experimental-webgl",{antialias:!0});V.WEBGL=!!e,V.WEBGL&&(V.ANTIALIAS=e.getContextAttributes().antialias,e.getShaderPrecisionFormat?e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0?V.FS_MAX_FLOAT_PRECISION="highp":e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?V.FS_MAX_FLOAT_PRECISION="mediump":V.FS_MAX_FLOAT_PRECISION="lowp":V.FS_MAX_FLOAT_PRECISION="mediump",V.DEPTH_BUFFER_BITS=e.getParameter(e.DEPTH_BITS),V.MAX_TEXTURE_SIZE=e.getParameter(e.MAX_TEXTURE_SIZE),V.MAX_CUBE_MAP_SIZE=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),V.MAX_RENDERBUFFER_SIZE=e.getParameter(e.MAX_RENDERBUFFER_SIZE),V.MAX_TEXTURE_UNITS=e.getParameter(e.MAX_COMBINED_TEXTURE_IMAGE_UNITS),V.MAX_TEXTURE_IMAGE_UNITS=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),V.MAX_VERTEX_ATTRIBS=e.getParameter(e.MAX_VERTEX_ATTRIBS),V.MAX_VERTEX_UNIFORM_VECTORS=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),V.MAX_FRAGMENT_UNIFORM_VECTORS=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),V.MAX_VARYING_VECTORS=e.getParameter(e.MAX_VARYING_VECTORS),e.getSupportedExtensions().forEach((function(e){V.SUPPORTED_EXTENSIONS[e]=!0})),V.depthTexturesSupported=V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture)}const z=["webgl","experimental-webgl","webkit-3d","moz-webgl","moz-glweb20"];class U extends A{get type(){return"Canvas"}constructor(e,t={}){super(e,t),this._backgroundColor=u.vec3([t.backgroundColor?t.backgroundColor[0]:1,t.backgroundColor?t.backgroundColor[1]:1,t.backgroundColor?t.backgroundColor[2]:1]),this._backgroundColorFromAmbientLight=!!t.backgroundColorFromAmbientLight,this.canvas=t.canvas,this.gl=null,this.webgl2=!1,this.transparent=!!t.transparent,this.contextAttr=t.contextAttr||{},this.contextAttr.alpha=this.transparent,this.contextAttr.preserveDrawingBuffer=!!this.contextAttr.preserveDrawingBuffer,this.contextAttr.stencil=!1,this.contextAttr.premultipliedAlpha=!!this.contextAttr.premultipliedAlpha,this.contextAttr.antialias=!1!==this.contextAttr.antialias,this.canvas.width=this.canvas.clientWidth,this.canvas.height=this.canvas.clientHeight,this.boundary=[this.canvas.offsetLeft,this.canvas.offsetTop,this.canvas.clientWidth,this.canvas.clientHeight],this._initWebGL(t);const i=this;this.canvas.addEventListener("webglcontextlost",this._webglcontextlostListener=function(e){console.time("webglcontextrestored"),i.scene._webglContextLost(),i.fire("webglcontextlost"),e.preventDefault()},!1),this.canvas.addEventListener("webglcontextrestored",this._webglcontextrestoredListener=function(e){i._initWebGL(),i.gl&&(i.scene._webglContextRestored(i.gl),i.fire("webglcontextrestored",i.gl),e.preventDefault()),console.timeEnd("webglcontextrestored")},!1);let s=null,r=null,o=null,a=null,n=null,l=null,h=null;this._tick=this.scene.on("tick",(function(){const e=i.canvas,t=window.innerWidth!==s||window.innerHeight!==r,c=e.clientWidth!==o||e.clientHeight!==a,u=e.offsetLeft!==n||e.offsetTop!==l,p=e.parentElement;if(t||c||u||p!==h){if(i._spinner._adjustPosition(),c||u){const t=e.clientWidth,s=e.clientHeight;if(c){let t,i=0;for(const e in w.scenes)w.scenes.hasOwnProperty(e)&&(t=w.scenes[e],i+=t.canvas.canvas.clientWidth*t.canvas.canvas.clientHeight);d.memory.pixels=i,e.width=e.clientWidth,e.height=e.clientHeight}const r=i.boundary;r[0]=e.offsetLeft,r[1]=e.offsetTop,r[2]=t,r[3]=s,i.fire("boundary",r),o=t,a=s}t&&(s=window.innerWidth,r=window.innerHeight),u&&(n=e.offsetLeft,l=e.offsetTop),h=p}})),this._spinner=new k(this.scene,{canvas:this.canvas,elementId:t.spinnerElementId})}_createCanvas(){const e="xeokit-canvas-"+u.createUUID(),t=document.getElementsByTagName("body")[0],i=document.createElement("div"),s=i.style;s.height="100%",s.width="100%",s.padding="0",s.margin="0",s.background="rgba(0,0,0,0);",s.float="left",s.left="0",s.top="0",s.position="absolute",s.opacity="1.0",s["z-index"]="-10000",i.innerHTML+='<canvas id="'+e+'" style="width: 100%; height: 100%; float: left; margin: 0; padding: 0;"></canvas>',t.appendChild(i),this.canvas=document.getElementById(e)}_getElementXY(e){let t=0,i=0;for(;e;)t+=e.offsetLeft-e.scrollLeft,i+=e.offsetTop-e.scrollTop,e=e.offsetParent;return{x:t,y:i}}_initWebGL(){if(!this.gl)for(let e=0;!this.gl&&e<z.length;e++)try{this.gl=this.canvas.getContext(z[e],this.contextAttr)}catch(e){}if(this.gl||(this.error("Failed to get a WebGL context"),this.fire("webglContextFailed",!0,!0)),this.gl)if(this.webgl2)this.gl.hint(this.gl.FRAGMENT_SHADER_DERIVATIVE_HINT,this.gl.FASTEST);else{if(V.SUPPORTED_EXTENSIONS.OES_standard_derivatives){const e=this.gl.getExtension("OES_standard_derivatives");this.gl.hint(e.FRAGMENT_SHADER_DERIVATIVE_HINT_OES,this.gl.FASTEST)}V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&this.gl.getExtension("EXT_frag_depth"),V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture&&this.gl.getExtension("WEBGL_depth_texture")}}set backgroundColorFromAmbientLight(e){this._backgroundColorFromAmbientLight=!1!==e}get backgroundColorFromAmbientLight(){return this._backgroundColorFromAmbientLight}set backgroundColor(e){e?(this._backgroundColor[0]=e[0],this._backgroundColor[1]=e[1],this._backgroundColor[2]=e[2]):(this._backgroundColor[0]=1,this._backgroundColor[1]=1,this._backgroundColor[2]=1),this.glRedraw()}get backgroundColor(){return this._backgroundColor}getSnapshot(e){throw"Canvas#getSnapshot() has been replaced by Viewer#getSnapshot() - use that method instead."}readPixels(e,t,i,s){return this.scene._renderer.readPixels(e,t,i,s)}loseWebGLContext(){this.canvas.loseContext&&this.canvas.loseContext()}get spinner(){return this._spinner}destroy(){this.scene.off(this._tick),this._spinner._destroy(),this.canvas.removeEventListener("webglcontextlost",this._webglcontextlostListener),this.canvas.removeEventListener("webglcontextrestored",this._webglcontextrestoredListener),this.gl=null,super.destroy()}}class G{constructor(e){this._scene=e,this._matPool=[],this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.reset()}reset(){this._matPoolNextFreeIndex=0,this._rtcViewMats={},this._rtcPickViewMats={},this.gl=this._scene.canvas.gl,this.lastProgramId=null,this.pbrEnabled=!1,this.withSAO=!1,this.backfaces=!1,this.frontface=!0,this.textureUnit=0,this.drawElements=0,this.drawArrays=0,this.useProgram=0,this.bindTexture=0,this.bindArray=0,this.pass=0,this.shadowViewMatrix=null,this.shadowProjMatrix=null,this.pickViewMatrix=null,this.pickProjMatrix=null,this.pickZNear=.01,this.pickZFar=5e3,this.pickInvisible=!1,this.lineWidth=1}getRTCViewMatrix(e,t){let i=this._rtcViewMats[e];return i||(i=this._getNewMat(),I(this._scene.camera.viewMatrix,t,i),this._rtcViewMats[e]=i),i}getRTCPickViewMatrix(e,t){let i=this._rtcPickViewMats[e];if(!i){i=this._getNewMat();const s=this.pickViewMatrix||this._scene.camera.viewMatrix;I(s,t,i),this._rtcPickViewMats[e]=i}return i}_getNewMat(){let e=this._matPool[this._matPoolNextFreeIndex];return e||(e=u.mat4(),this._matPool[this._matPoolNextFreeIndex]=e),this._matPoolNextFreeIndex++,e}}const X=function(){const e=document.createElement("canvas"),t=String.fromCharCode;if(!e.getContext)return{saveAsBMP:function(){},saveAsPNG:function(){},saveAsJPEG:function(){}};const i=!!e.getContext("2d").getImageData,s=!!e.toDataURL,r=!!window.btoa,o=function(e){let i="";const s=e.width,r=e.height;i+="BM";let o=s*r*4+54;i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),o=Math.floor(o/256),i+=t(o%256),i+=t(0,0,0,0,54,0,0,0),i+=t(40,0,0,0);let a=s;i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),a=Math.floor(a/256),i+=t(a%256),a=Math.floor(a/256),i+=t(a%256);let n=r;i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),n=Math.floor(n/256),i+=t(n%256),i+=t(1,0,32,0),i+=t(0,0,0,0);let l=s*r*4;i+=t(l%256),l=Math.floor(l/256),i+=t(l%256),l=Math.floor(l/256),i+=t(l%256),l=Math.floor(l/256),i+=t(l%256),i+=t(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const h=e.data;let c,u,d,p,_="",f=r;do{for(d=s*(f-1)*4,p="",c=0;c<s;c++)u=4*c,p+=t(h[d+u+2],h[d+u+1],h[d+u],h[d+u+3]);_+=p}while(--f);return function(e){let i,s,r="";if("string"==typeof e)r=e;else for(s=e,i=0;i<s.length;i++)r+=t(s[i]);return btoa(r)}(i+_)},a=function(e){window.open(e)||(document.location.href=e)},n=function(e,t){return"data:"+t+";base64,"+e},l=function(e){const t=document.createElement("img");return t.src=e,t},h=function(e,t,i,s){if(t&&i){const r=document.createElement("canvas");r.width=t,r.height=i,r.style.width=t+"px",r.style.height=i+"px";const o=r.getContext("2d");return s?(o.save(),o.scale(1,-1),o.imageSmoothingEnabled=!0,o.drawImage(e,0,0,e.width,e.height,0,0,t,-i),o.restore()):(o.imageSmoothingEnabled=!0,o.drawImage(e,0,0,e.width,e.height,0,0,t,i)),r}return e};return{saveAsPNG:function(e,t,i,r,o){if(!s)return!1;const n=h(e,i,r,o).toDataURL("image/png");return t?l(n):(a(n),!0)},saveAsJPEG:function(e,t,i,r,o){if(!s)return!1;const n="image/jpeg",c=h(e,i,r,o).toDataURL(n);return 5==c.indexOf(n)&&(t?l(c):(a(c),!0))},saveAsBMP:function(e,t,c,u,d){if(!(s&&i&&r))return!1;const p="image/bmp",_=function(e){const t=parseInt(e.width),i=parseInt(e.height);return e.getContext("2d").getImageData(0,0,t,i)}(h(e,c,u,d)),f=o(_);return t?l(n(f,p)):(a(n(f,p)),!0)}}}();class H{constructor(e,t,i){i=i||{},this.gl=t,this.allocated=!1,this.canvas=e,this.buffer=null,this.bound=!1,this.size=i.size,this._hasDepthTexture=!!i.depthTexture}setSize(e){this.size=e}webglContextRestored(e){this.gl=e,this.buffer=null,this.allocated=!1,this.bound=!1}bind(){if(this._touch(),this.bound)return;const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,this.buffer.framebuf),this.bound=!0}_touch(){let e,t;const i=this.gl;if(this.size?(e=this.size[0],t=this.size[1]):(e=i.drawingBufferWidth,t=i.drawingBufferHeight),this.buffer){if(this.buffer.width===e&&this.buffer.height===t)return;i.deleteTexture(this.buffer.texture),i.deleteFramebuffer(this.buffer.framebuf),i.deleteRenderbuffer(this.buffer.renderbuf)}const s=i.createTexture();let r;i.bindTexture(i.TEXTURE_2D,s),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.RGBA,e,t,0,i.RGBA,i.UNSIGNED_BYTE,null),this._hasDepthTexture&&(r=i.createTexture(),i.bindTexture(i.TEXTURE_2D,r),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MAG_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_MIN_FILTER,i.NEAREST),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_S,i.CLAMP_TO_EDGE),i.texParameteri(i.TEXTURE_2D,i.TEXTURE_WRAP_T,i.CLAMP_TO_EDGE),i.texImage2D(i.TEXTURE_2D,0,i.DEPTH_COMPONENT,e,t,0,i.DEPTH_COMPONENT,i.UNSIGNED_INT,null));const o=i.createRenderbuffer();i.bindRenderbuffer(i.RENDERBUFFER,o),i.renderbufferStorage(i.RENDERBUFFER,i.DEPTH_COMPONENT16,e,t);const a=i.createFramebuffer();if(i.bindFramebuffer(i.FRAMEBUFFER,a),i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.TEXTURE_2D,s,0),this._hasDepthTexture?i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,r,0):i.framebufferRenderbuffer(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.RENDERBUFFER,o),i.bindTexture(i.TEXTURE_2D,null),i.bindRenderbuffer(i.RENDERBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,null),i.bindFramebuffer(i.FRAMEBUFFER,a),!i.isFramebuffer(a))throw"Invalid framebuffer";i.bindFramebuffer(i.FRAMEBUFFER,null);const n=i.checkFramebufferStatus(i.FRAMEBUFFER);switch(n){case i.FRAMEBUFFER_COMPLETE:break;case i.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case i.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:throw"Incomplete framebuffer: FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case i.FRAMEBUFFER_UNSUPPORTED:throw"Incomplete framebuffer: FRAMEBUFFER_UNSUPPORTED";default:throw"Incomplete framebuffer: "+n}this.buffer={framebuf:a,renderbuf:o,texture:s,depthTexture:r,width:e,height:t},this.bound=!1}clear(){if(!this.bound)throw"Render buffer not bound";const e=this.gl;e.clear(e.COLOR_BUFFER_BIT|e.DEPTH_BUFFER_BIT)}read(e,t){const i=e,s=this.gl.drawingBufferHeight-t,r=new Uint8Array(4),o=this.gl;return o.readPixels(i,s,1,1,o.RGBA,o.UNSIGNED_BYTE,r),r}readImage(e){const t=this.gl,i=this._getImageDataCache(),s=i.pixelData,r=i.canvas,o=i.imageData,a=i.context;t.readPixels(0,0,this.buffer.width,this.buffer.height,t.RGBA,t.UNSIGNED_BYTE,s),o.data.set(s),a.putImageData(o,0,0);const n=e.width||r.width,l=e.height||r.height,h=e.format||"jpeg",c=!0;let u;switch(h){case"jpeg":u=X.saveAsJPEG(r,!0,n,l,c);break;case"png":u=X.saveAsPNG(r,!0,n,l,c);break;case"bmp":u=X.saveAsBMP(r,!0,n,l,c);break;default:console.error("Unsupported image format: '"+h+"' - supported types are 'jpeg', 'bmp' and 'png' - defaulting to 'jpeg'"),u=X.saveAsJPEG(r,!0,n,l,c)}return u.src}_getImageDataCache(){const e=this.buffer.width,t=this.buffer.height;let i=this._imageDataCache;if(i&&(i.width===e&&i.height===t||(this._imageDataCache=null,i=null)),!i){const s=document.createElement("canvas");s.width=e,s.height=t;const r=s.getContext("2d"),o=r.createImageData(e,t);i={pixelData:new Uint8Array(e*t*4),canvas:s,context:r,imageData:o,width:e,height:t},this._imageDataCache=i}return i}unbind(){const e=this.gl;e.bindFramebuffer(e.FRAMEBUFFER,null),this.bound=!1}getTexture(){const e=this;return this._texture||(this._texture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.texture||(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.texture),0))},unbind:function(t){e.buffer&&e.buffer.texture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}hasDepthTexture(){return this._hasDepthTexture}getDepthTexture(){if(!this._hasDepthTexture)return null;const e=this;return this._depthTexture||(this._dethTexture={renderBuffer:this,bind:function(t){return!(!e.buffer||!e.buffer.depthTexture||(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,e.buffer.depthTexture),0))},unbind:function(t){e.buffer&&e.buffer.depthTexture&&(e.gl.activeTexture(e.gl["TEXTURE"+t]),e.gl.bindTexture(e.gl.TEXTURE_2D,null))}})}destroy(){if(this.allocated){const e=this.gl;e.deleteTexture(this.buffer.texture),e.deleteTexture(this.buffer.depthTexture),e.deleteFramebuffer(this.buffer.framebuf),e.deleteRenderbuffer(this.buffer.renderbuf),this.allocated=!1,this.buffer=null,this.bound=!1}this._imageDataCache=null,this._texture=null,this._depthTexture=null}}class W{constructor(){this.entity=null,this.primitive=null,this.primIndex=-1,this._canvasPos=new Int16Array([0,0]),this._origin=new Float64Array([0,0,0]),this._direction=new Float64Array([0,0,0]),this._indices=new Int32Array(3),this._localPos=new Float64Array([0,0,0]),this._worldPos=new Float64Array([0,0,0]),this._viewPos=new Float64Array([0,0,0]),this._bary=new Float64Array([0,0,0]),this._worldNormal=new Float64Array([0,0,0]),this._uv=new Float64Array([0,0]),this.reset()}get canvasPos(){return this._gotCanvasPos?this._canvasPos:null}set canvasPos(e){e?(this._canvasPos[0]=e[0],this._canvasPos[1]=e[1],this._gotCanvasPos=!0):this._gotCanvasPos=!1}get origin(){return this._gotOrigin?this._origin:null}set origin(e){e?(this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this._gotOrigin=!0):this._gotOrigin=!1}get direction(){return this._gotDirection?this._direction:null}set direction(e){e?(this._direction[0]=e[0],this._direction[1]=e[1],this._direction[2]=e[2],this._gotDirection=!0):this._gotDirection=!1}get indices(){return this.entity&&this._gotIndices?this._indices:null}set indices(e){e?(this._indices[0]=e[0],this._indices[1]=e[1],this._indices[2]=e[2],this._gotIndices=!0):this._gotIndices=!1}get localPos(){return this.entity&&this._gotLocalPos?this._localPos:null}set localPos(e){e?(this._localPos[0]=e[0],this._localPos[1]=e[1],this._localPos[2]=e[2],this._gotLocalPos=!0):this._gotLocalPos=!1}get worldPos(){return this.entity&&this._gotWorldPos?this._worldPos:null}set worldPos(e){e?(this._worldPos[0]=e[0],this._worldPos[1]=e[1],this._worldPos[2]=e[2],this._gotWorldPos=!0):this._gotWorldPos=!1}get viewPos(){return this.entity&&this._gotViewPos?this._viewPos:null}set viewPos(e){e?(this._viewPos[0]=e[0],this._viewPos[1]=e[1],this._viewPos[2]=e[2],this._gotViewPos=!0):this._gotViewPos=!1}get bary(){return this.entity&&this._gotBary?this._bary:null}set bary(e){e?(this._bary[0]=e[0],this._bary[1]=e[1],this._bary[2]=e[2],this._gotBary=!0):this._gotBary=!1}get worldNormal(){return this.entity&&this._gotWorldNormal?this._worldNormal:null}set worldNormal(e){e?(this._worldNormal[0]=e[0],this._worldNormal[1]=e[1],this._worldNormal[2]=e[2],this._gotWorldNormal=!0):this._gotWorldNormal=!1}get uv(){return this.entity&&this._gotUV?this._uv:null}set uv(e){e?(this._uv[0]=e[0],this._uv[1]=e[1],this._gotUV=!0):this._gotUV=!1}reset(){this.entity=null,this.primIndex=-1,this.primitive=null,this._gotCanvasPos=!1,this._gotOrigin=!1,this._gotDirection=!1,this._gotIndices=!1,this._gotLocalPos=!1,this._gotWorldPos=!1,this._gotViewPos=!1,this._gotBary=!1,this._gotWorldNormal=!1,this._gotUV=!1}}class Y{constructor(e,t,i){if(this.allocated=!1,this.compiled=!1,this.handle=e.createShader(t),this.handle){if(this.allocated=!0,e.shaderSource(this.handle,i),e.compileShader(this.handle),this.compiled=e.getShaderParameter(this.handle,e.COMPILE_STATUS),!this.compiled&&!e.isContextLost()){const t=i.split("\n"),s=[];for(let e=0;e<t.length;e++)s.push(e+1+": "+t[e]+"\n");this.errors=[],this.errors.push(""),this.errors.push(e.getShaderInfoLog(this.handle)),this.errors=this.errors.concat(s.join(""))}}else this.errors=["Failed to allocate"]}destroy(){}}class q{constructor(e,t){this.bindTexture=function(i,s){return!!i.bind(s)&&(e.uniform1i(t,s),!0)}}}class K{constructor(e,t){this._gl=e,this.location=t}bindArrayBuffer(e){e&&(e.bind(),this._gl.enableVertexAttribArray(this.location),this._gl.vertexAttribPointer(this.location,e.itemSize,e.itemType,e.normalized,e.stride,e.offset))}}const Z=new e({});function Q(e){const t=[];let i,s;for(let r=0,o=e.length;r<o;r++)i=e[r],s=i.indexOf("/"),s>0&&"/"===i.charAt(s+1)&&(i=i.substring(0,s)),t.push(i);return t.join("\n")}function $(e){console.error(e.join("\n"))}class J{constructor(e,t){this.id=Z.addItem({}),this.source=t,this.init(e)}init(e){if(this.gl=e,this.allocated=!1,this.compiled=!1,this.linked=!1,this.validated=!1,this.errors=null,this.uniforms={},this.samplers={},this.attributes={},this._vertexShader=new Y(e,e.VERTEX_SHADER,Q(this.source.vertex)),this._fragmentShader=new Y(e,e.FRAGMENT_SHADER,Q(this.source.fragment)),!this._vertexShader.allocated)return this.errors=["Vertex shader failed to allocate"].concat(this._vertexShader.errors),void $(this.errors);if(!this._fragmentShader.allocated)return this.errors=["Fragment shader failed to allocate"].concat(this._fragmentShader.errors),void $(this.errors);if(this.allocated=!0,!this._vertexShader.compiled)return this.errors=["Vertex shader failed to compile"].concat(this._vertexShader.errors),void $(this.errors);if(!this._fragmentShader.compiled)return this.errors=["Fragment shader failed to compile"].concat(this._fragmentShader.errors),void $(this.errors);let t,i,s,r,o;if(this.compiled=!0,this.handle=e.createProgram(),!this.handle)return void(this.errors=["Failed to allocate program"]);if(e.attachShader(this.handle,this._vertexShader.handle),e.attachShader(this.handle,this._fragmentShader.handle),e.linkProgram(this.handle),this.linked=e.getProgramParameter(this.handle,e.LINK_STATUS),this.validated=!0,!this.linked||!this.validated)return this.errors=[],this.errors.push(""),this.errors.push(e.getProgramInfoLog(this.handle)),this.errors.push("\nVertex shader:\n"),this.errors=this.errors.concat(this.source.vertex),this.errors.push("\nFragment shader:\n"),this.errors=this.errors.concat(this.source.fragment),void $(this.errors);const a=e.getProgramParameter(this.handle,e.ACTIVE_UNIFORMS);for(i=0;i<a;++i)s=e.getActiveUniform(this.handle,i),s&&(r=s.name,"\0"===r[r.length-1]&&(r=r.substr(0,r.length-1)),o=e.getUniformLocation(this.handle,r),s.type===e.SAMPLER_2D||s.type===e.SAMPLER_CUBE||35682===s.type?this.samplers[r]=new q(e,o):this.uniforms[r]=o);const n=e.getProgramParameter(this.handle,e.ACTIVE_ATTRIBUTES);for(i=0;i<n;i++)t=e.getActiveAttrib(this.handle,i),t&&(o=e.getAttribLocation(this.handle,t.name),this.attributes[t.name]=new K(e,o));this.allocated=!0}bind(){this.allocated&&this.gl.useProgram(this.handle)}getLocation(e){if(this.allocated)return this.uniforms[e]}getAttribute(e){if(this.allocated)return this.attributes[e]}bindTexture(e,t,i){if(!this.allocated)return!1;const s=this.samplers[e];return!!s&&s.bindTexture(t,i)}destroy(){this.allocated&&(Z.removeItem(this.id),this.gl.deleteProgram(this.handle),this.gl.deleteShader(this._vertexShader.handle),this.gl.deleteShader(this._fragmentShader.handle),this.handle=null,this.attributes=null,this.uniforms=null,this.samplers=null,this.allocated=!1)}}class ee{constructor(e,t,i,s,r,o,a,n,l){switch(this._gl=e,this.type=t,this.allocated=!1,i.constructor){case Uint8Array:this.itemType=e.UNSIGNED_BYTE,this.itemByteSize=1;break;case Int8Array:this.itemType=e.BYTE,this.itemByteSize=1;break;case Uint16Array:this.itemType=e.UNSIGNED_SHORT,this.itemByteSize=2;break;case Int16Array:this.itemType=e.SHORT,this.itemByteSize=2;break;case Uint32Array:this.itemType=e.UNSIGNED_INT,this.itemByteSize=4;break;case Int32Array:this.itemType=e.INT,this.itemByteSize=4;break;default:this.itemType=e.FLOAT,this.itemByteSize=4}this.usage=o,this.length=0,this.dataLength=s,this.numItems=0,this.itemSize=r,this.normalized=!!a,this.stride=n||0,this.offset=l||0,this._allocate(i)}_allocate(e){if(this.allocated=!1,this._handle=this._gl.createBuffer(),!this._handle)throw"Failed to allocate WebGL ArrayBuffer";this._handle&&(this._gl.bindBuffer(this.type,this._handle),this._gl.bufferData(this.type,e.length>this.dataLength?e.slice(0,this.dataLength):e,this.usage),this._gl.bindBuffer(this.type,null),this.length=e.length,this.numItems=this.length/this.itemSize,this.allocated=!0)}setData(e,t){this.allocated&&(e.length+(t||0)>this.length?(this.destroy(),this._allocate(e)):(this._gl.bindBuffer(this.type,this._handle),t||0===t?this._gl.bufferSubData(this.type,t*this.itemByteSize,e):this._gl.bufferData(this.type,e,this.usage),this._gl.bindBuffer(this.type,null)))}bind(){this.allocated&&this._gl.bindBuffer(this.type,this._handle)}unbind(){this.allocated&&this._gl.bindBuffer(this.type,null)}destroy(){this.allocated&&(this._gl.deleteBuffer(this._handle),this._handle=null,this.allocated=!1)}}class te{constructor(e,t){this.scene=e,this.aabb=u.AABB3(),this.rtcCenter=u.vec3(t),this.rtcCenterHash=this.rtcCenter.join(),this.numMarkers=0,this.markers={},this.markerList=[],this.markerIndices={},this.positions=[],this.indices=[],this.positionsBuf=null,this.lenPositionsBuf=0,this.indicesBuf=null,this.sectionPlanesActive=[],this.culledBySectionPlanes=!1,this.occlusionTestList=[],this.lenOcclusionTestList=0,this.pixels=[],this.aabbDirty=!1,this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!1}addMarker(e){this.markers[e.id]=e,this.markerListDirty=!0,this.numMarkers++}markerWorldPosUpdated(e){if(!this.markers[e.id])return;const t=this.markerIndices[e.id];this.positions[3*t+0]=e.worldPos[0],this.positions[3*t+1]=e.worldPos[1],this.positions[3*t+2]=e.worldPos[2],this.positionsDirty=!0}removeMarker(e){delete this.markers[e.id],this.markerListDirty=!0,this.numMarkers--}update(){this.markerListDirty&&(this._buildMarkerList(),this.markerListDirty=!1,this.positionsDirty=!0,this.occlusionTestListDirty=!0),this.positionsDirty&&(this._buildPositions(),this.positionsDirty=!1,this.aabbDirty=!0,this.vbosDirty=!0),this.aabbDirty&&(this._buildAABB(),this.aabbDirty=!1),this.vbosDirty&&(this._buildVBOs(),this.vbosDirty=!1),this.occlusionTestListDirty&&this._buildOcclusionTestList(),this._updateActiveSectionPlanes()}_buildMarkerList(){for(var e in this.numMarkers=0,this.markers)this.markers.hasOwnProperty(e)&&(this.markerList[this.numMarkers]=this.markers[e],this.markerIndices[e]=this.numMarkers,this.numMarkers++);this.markerList.length=this.numMarkers}_buildPositions(){let e=0;for(let t=0;t<this.numMarkers;t++)if(this.markerList[t]){const i=this.markerList[t].worldPos;this.positions[e++]=i[0],this.positions[e++]=i[1],this.positions[e++]=i[2],this.indices[t]=t}this.positions.length=3*this.numMarkers,this.indices.length=this.numMarkers}_buildAABB(){const e=this.aabb;u.collapseAABB3(e),u.expandAABB3Points3(e,this.positions);const t=this.rtcCenter;e[0]+=t[0],e[1]+=t[1],e[2]+=t[2],e[3]+=t[0],e[4]+=t[1],e[5]+=t[2]}_buildVBOs(){if(this.positionsBuf){if(this.lenPositionsBuf===this.positions.length)return void this.positionsBuf.setData(this.positions);this.positionsBuf.destroy(),this.positionsBuf=null,this.indicesBuf.destroy(),this.indicesBuf=null}const e=this.scene.canvas.gl,t=3*this.numMarkers,i=this.numMarkers;this.positionsBuf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this.positions),t,3,e.STATIC_DRAW),this.indicesBuf=new ee(e,e.ELEMENT_ARRAY_BUFFER,new Uint16Array(this.indices),i,1,e.STATIC_DRAW),this.lenPositionsBuf=this.positions.length}_buildOcclusionTestList(){const e=this.scene.canvas,t=this.scene.camera.perspective.near,i=e.boundary,s=i[2],r=i[3];let o=0;this.lenOcclusionTestList=0;for(let e=0;e<this.numMarkers;e++){const i=this.markerList[e];if(i.viewPos[2]>-t){i._setVisible(!1);continue}const a=i.canvasPos,n=a[0],l=a[1];n+10<0||l+10<0||n-10>s||l-10>r?i._setVisible(!1):!i.entity||i.entity.visible?i.occludable?(this.occlusionTestList[this.lenOcclusionTestList++]=i,this.pixels[o++]=n,this.pixels[o++]=l):i._setVisible(!0):i._setVisible(!1)}}_updateActiveSectionPlanes(){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i<t;i++){const t=e[i];if(t.active){const e=u.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return void(this.culledBySectionPlanes=!0);const s=0===e;this.sectionPlanesActive[i]=s}else this.sectionPlanesActive[i]=!1}this.culledBySectionPlanes=!1}destroy(){this.markers={},this.markerList.length=0,this.positionsBuf&&this.positionsBuf.destroy(),this.indicesBuf&&this.indicesBuf.destroy()}}const ie=u.vec3([1,0,0]),se=u.vec3();class re{constructor(e){this._scene=e,this._occlusionLayers={},this._occlusionLayersList=[],this._occlusionLayersListDirty=!1,this._shaderSource=null,this._program=null,this._shaderSourceHash=null,this._shaderSourceDirty=!0,this._programDirty=!1,this._markersToOcclusionLayersMap={},this._onCameraViewMatrix=e.camera.on("viewMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCameraProjMatrix=e.camera.on("projMatrix",(()=>{this._occlusionTestListDirty=!0})),this._onCanvasBoundary=e.canvas.on("boundary",(()=>{this._occlusionTestListDirty=!0}))}addMarker(e){const t=e.rtcCenter.join();let i=this._occlusionLayers[t];i||(i=new te(this._scene,e.rtcCenter),this._occlusionLayers[i.rtcCenterHash]=i,this._occlusionLayersListDirty=!0),i.addMarker(e),this._markersToOcclusionLayersMap[e.id]=i,this._occlusionTestListDirty=!0}markerWorldPosUpdated(e){const t=this._markersToOcclusionLayersMap[e.id];if(!t)return void e.error("Marker has not been added to OcclusionTester");const i=e.rtcCenter.join();if(i!==t.rtcCenterHash){1===t.numMarkers?(t.destroy(),delete this._occlusionLayers[t.rtcCenterHash],this._occlusionLayersListDirty=!0):t.removeMarker(e);let s=this._occlusionLayers[i];s||(s=new te(this._scene,e.rtcCenter),this._occlusionLayers[i]=t,this._occlusionLayersListDirty=!0),s.addMarker(e),this._markersToOcclusionLayersMap[e.id]=s}else t.markerWorldPosUpdated(e)}removeMarker(e){const t=e.rtcCenter.join();let i=this._occlusionLayers[t];i&&(1===i.numMarkers?(i.destroy(),delete this._occlusionLayers[i.rtcCenterHash],this._occlusionLayersListDirty=!0):i.removeMarker(e),delete this._markersToOcclusionLayersMap[e.id])}get needOcclusionTest(){return this._occlusionTestListDirty}bindRenderBuf(){const e=[this._scene.canvas.canvas.id,this._scene._sectionPlanesState.getHash()].join(";");if(e!==this._shaderSourceHash&&(this._shaderSourceHash=e,this._shaderSourceDirty=!0),this._shaderSourceDirty&&(this._buildShaderSource(),this._shaderSourceDirty=!1,this._programDirty=!0),this._programDirty&&(this._buildProgram(),this._programDirty=!1,this._occlusionTestListDirty=!0),this._occlusionLayersListDirty&&(this._buildOcclusionLayersList(),this._occlusionLayersListDirty=!1),this._occlusionTestListDirty){for(let e=0,t=this._occlusionLayersList.length;e<t;e++)this._occlusionLayersList[e].occlusionTestListDirty=!0;this._occlusionTestListDirty=!1}this._readPixelBuf=this._readPixelBuf||(this._readPixelBuf=new H(this._scene.canvas.canvas,this._scene.canvas.gl)),this._readPixelBuf.bind(),this._readPixelBuf.clear()}_buildOcclusionLayersList(){let e=0;for(let t in this._occlusionLayers)this._occlusionLayers.hasOwnProperty(t)&&(this._occlusionLayersList[e++]=this._occlusionLayers[t]);this._occlusionLayersList.length=e}_buildShaderSource(){this._shaderSource={vertex:this._buildVertexShaderSource(),fragment:this._buildFragmentShaderSource()}}_buildVertexShaderSource(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// OcclusionTester vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("attribute vec3 position;"),i.push("uniform mat4 modelMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&i.push("varying vec4 vWorldPosition;"),i.push("void main(void) {"),i.push("vec4 worldPosition = vec4(position, 1.0); "),i.push("   vec4 viewPosition = viewMatrix * worldPosition;"),t&&i.push("   vWorldPosition = worldPosition;"),i.push("   vec4 clipPos = projMatrix * viewPosition;"),i.push("   gl_Position = clipPos;"),i.push("   gl_PointSize = 20.0;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("}"),i}_buildFragmentShaderSource(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// OcclusionTester fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("void main(void) {"),i){s.push("  float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("   gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); "),s.push("}"),s}_buildProgram(){this._program&&this._program.destroy();const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}drawMarkers(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e._sectionPlanesState,r=e.camera,o=e.camera.project;if(V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&e.logarithmicDepthBufferEnabled&&t.getExtension("EXT_frag_depth"),i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,r._project._state.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,i=this._occlusionLayersList.length;e<i;e++){const i=this._occlusionLayersList[e];if(i.update(),i.culledBySectionPlanes)continue;const o=i.rtcCenter;t.uniformMatrix4fv(this._uViewMatrix,!1,I(r.viewMatrix,o));const a=s.sectionPlanes.length;if(a>0){const e=s.sectionPlanes;for(let s=0;s<a;s++){const r=this._uSectionPlanes[s],a=i.sectionPlanesActive[s];if(t.uniform1i(r.active,a?1:0),a){const i=e[s];t.uniform3fv(r.pos,O(i.dist,i.dir,o,se)),t.uniform3fv(r.dir,i.dir)}}}this._aPosition.bindArrayBuffer(i.positionsBuf);const n=i.indicesBuf;n.bind(),t.drawElements(t.POINTS,n.numItems,n.itemType,0)}}doOcclusionTest(){{const e=255*ie[0],t=255*ie[1],i=255*ie[2];for(let s=0,r=this._occlusionLayersList.length;s<r;s++){const r=this._occlusionLayersList[s];for(let s=0;s<r.lenOcclusionTestList;s++){const o=r.occlusionTestList[s],a=2*s,n=this._readPixelBuf.read(r.pixels[a],r.pixels[a+1]),l=n[0]===e&&n[1]===t&&n[2]===i;o._setVisible(l)}}}}unbindRenderBuf(){this._readPixelBuf.unbind()}destroy(){if(!this.destroyed){for(let e=0,t=this._occlusionLayersList.length;e<t;e++)this._occlusionLayersList[e].destroy();this._program&&this._program.destroy(),this._scene.camera.off(this._onCameraViewMatrix),this._scene.camera.off(this._onCameraProjMatrix),this._scene.canvas.off(this._onCanvasBoundary),this.destroyed=!0}}}const oe=u.vec2();class ae{constructor(e){this._scene=e,this._numSamples=null,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uRandomSeed=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null}render(e){if(this._build(),this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(s.camera.projMatrix,t),t)})());const t=this._scene.canvas.gl,i=this._program,s=this._scene,r=s.sao,o=t.drawingBufferWidth,a=t.drawingBufferHeight,n=s.camera.project._state,l=n.near,h=n.far,c=n.matrix,d=this._getInverseProjectMat(),p=Math.random(),_="perspective"===s.camera.projection;oe[0]=o,oe[1]=a,t.getExtension("OES_standard_derivatives"),t.viewport(0,0,o,a),t.clearColor(0,0,0,1),t.disable(t.DEPTH_TEST),t.disable(t.BLEND),t.frontFace(t.CCW),t.clear(t.COLOR_BUFFER_BIT),i.bind(),t.uniform1f(this._uCameraNear,l),t.uniform1f(this._uCameraFar,h),t.uniformMatrix4fv(this._uCameraProjectionMatrix,!1,c),t.uniformMatrix4fv(this._uCameraInverseProjectionMatrix,!1,d),t.uniform1i(this._uPerspective,_),t.uniform1f(this._uScale,r.scale*(h/5)),t.uniform1f(this._uIntensity,r.intensity),t.uniform1f(this._uBias,r.bias),t.uniform1f(this._uKernelRadius,r.kernelRadius),t.uniform1f(this._uMinResolution,r.minResolution),t.uniform2fv(this._uViewport,oe),t.uniform1f(this._uRandomSeed,p);const f=V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture?e.getDepthTexture():e.getTexture();i.bindTexture(this._uDepthTexture,f,0),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),t.drawElements(t.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}_build(){let e=!1;const t=this._scene.sao;if(t.numSamples!==this._numSamples&&(this._numSamples=Math.floor(t.numSamples),e=!0),!e)return;const i=this._scene.canvas.gl;if(this._program&&(this._program.destroy(),this._program=null),this._program=new J(i,{vertex:["precision highp float;\n                    precision highp int;\n                    \n                    attribute vec3 aPosition;\n                    attribute vec2 aUV;            \n                    \n                    varying vec2 vUV;\n                    \n                    void main () {\n                        gl_Position = vec4(aPosition, 1.0);\n                        vUV = aUV;\n                    }"],fragment:[`#extension GL_OES_standard_derivatives : require              \n                precision highp float;\n                precision highp int;           \n                \n                #define NORMAL_TEXTURE 0\n                #define PI 3.14159265359\n                #define PI2 6.28318530718\n                #define EPSILON 1e-6\n                #define NUM_SAMPLES ${this._numSamples}\n                #define NUM_RINGS 4              \n            \n                varying vec2        vUV;\n            \n                uniform sampler2D   uDepthTexture;\n               \n                uniform float       uCameraNear;\n                uniform float       uCameraFar;\n                uniform mat4        uProjectMatrix;\n                uniform mat4        uInverseProjectMatrix;\n                \n                uniform bool        uPerspective;\n\n                uniform float       uScale;\n                uniform float       uIntensity;\n                uniform float       uBias;\n                uniform float       uKernelRadius;\n                uniform float       uMinResolution;\n                uniform vec2        uViewport;\n                uniform float       uRandomSeed;\n\n                float pow2( const in float x ) { return x*x; }\n                \n                highp float rand( const in vec2 uv ) {\n                    const highp float a = 12.9898, b = 78.233, c = 43758.5453;\n                    highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI );\n                    return fract(sin(sn) * c);\n                }\n\n                vec3 packNormalToRGB( const in vec3 normal ) {\n                    return normalize( normal ) * 0.5 + 0.5;\n                }\n\n                vec3 unpackRGBToNormal( const in vec3 rgb ) {\n                    return 2.0 * rgb.xyz - 1.0;\n                }\n\n                const float packUpscale = 256. / 255.;\n                const float unpackDownScale = 255. / 256.; \n\n                const vec3 packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\n                const vec4 unPackFactors = unpackDownScale / vec4( packFactors, 1. );   \n\n                const float shiftRights = 1. / 256.;\n\n                vec4 packFloatToRGBA( const in float v ) {\n                    vec4 r = vec4( fract( v * packFactors ), v );\n                    r.yzw -= r.xyz * shiftRights; \n                    return r * packUpscale;\n                }\n\n                float unpackRGBAToFloat( const in vec4 v ) {                   \n                    return dot( floor( v * 255.0 + 0.5 ) / 255.0, unPackFactors );\n                }\n                \n                float perspectiveDepthToViewZ( const in float invClipZ, const in float near, const in float far ) {\n                    return ( near * far ) / ( ( far - near ) * invClipZ - far );\n                }\n\n                float orthographicDepthToViewZ( const in float linearClipZ, const in float near, const in float far ) {\n                    return linearClipZ * ( near - far ) - near;\n                }\n                \n                float getDepth( const in vec2 screenPosition ) {`+(V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture?"return texture2D(uDepthTexture, screenPosition).r;":"return unpackRGBAToFloat(texture2D( uDepthTexture, screenPosition));")+"}\n\n                float getViewZ( const in float depth ) {\n                     if (uPerspective) {\n                         return perspectiveDepthToViewZ( depth, uCameraNear, uCameraFar );\n                     } else {\n                        return orthographicDepthToViewZ( depth, uCameraNear, uCameraFar );\n                     }\n                }\n\n                vec3 getViewPos( const in vec2 screenPos, const in float depth, const in float viewZ ) {\n                \tfloat clipW = uProjectMatrix[2][3] * viewZ + uProjectMatrix[3][3];\n                \tvec4 clipPosition = vec4( ( vec3( screenPos, depth ) - 0.5 ) * 2.0, 1.0 );\n                \tclipPosition *= clipW; \n                \treturn ( uInverseProjectMatrix * clipPosition ).xyz;\n                }\n\n                vec3 getViewNormal( const in vec3 viewPosition, const in vec2 screenPos ) {               \n                    return normalize( cross( dFdx( viewPosition ), dFdy( viewPosition ) ) );\n                }\n\n                float scaleDividedByCameraFar;\n                float minResolutionMultipliedByCameraFar;\n\n                float getOcclusion( const in vec3 centerViewPosition, const in vec3 centerViewNormal, const in vec3 sampleViewPosition ) {\n                \tvec3 viewDelta = sampleViewPosition - centerViewPosition;\n                \tfloat viewDistance = length( viewDelta );\n                \tfloat scaledScreenDistance = scaleDividedByCameraFar * viewDistance;\n                \treturn max(0.0, (dot(centerViewNormal, viewDelta) - minResolutionMultipliedByCameraFar) / scaledScreenDistance - uBias) / (1.0 + pow2( scaledScreenDistance ) );\n                }\n\n                const float ANGLE_STEP = PI2 * float( NUM_RINGS ) / float( NUM_SAMPLES );\n                const float INV_NUM_SAMPLES = 1.0 / float( NUM_SAMPLES );\n\n                float getAmbientOcclusion( const in vec3 centerViewPosition ) {\n            \n                \tscaleDividedByCameraFar = uScale / uCameraFar;\n                \tminResolutionMultipliedByCameraFar = uMinResolution * uCameraFar;\n                \tvec3 centerViewNormal = getViewNormal( centerViewPosition, vUV );\n\n                \tfloat angle = rand( vUV + uRandomSeed ) * PI2;\n                \tvec2 radius = vec2( uKernelRadius * INV_NUM_SAMPLES ) / uViewport;\n                \tvec2 radiusStep = radius;\n\n                \tfloat occlusionSum = 0.0;\n                \tfloat weightSum = 0.0;\n\n                \tfor( int i = 0; i < NUM_SAMPLES; i ++ ) {\n                \t\tvec2 sampleUv = vUV + vec2( cos( angle ), sin( angle ) ) * radius;\n                \t\tradius += radiusStep;\n                \t\tangle += ANGLE_STEP;\n\n                \t\tfloat sampleDepth = getDepth( sampleUv );\n                \t\tif( sampleDepth >= ( 1.0 - EPSILON ) ) {\n                \t\t\tcontinue;\n                \t\t}\n\n                \t\tfloat sampleViewZ = getViewZ( sampleDepth );\n                \t\tvec3 sampleViewPosition = getViewPos( sampleUv, sampleDepth, sampleViewZ );\n                \t\tocclusionSum += getOcclusion( centerViewPosition, centerViewNormal, sampleViewPosition );\n                \t\tweightSum += 1.0;\n                \t}\n\n                \tif( weightSum == 0.0 ) discard;\n\n                \treturn occlusionSum * ( uIntensity / weightSum );\n                }\n\n                void main() {\n                \n                \tfloat centerDepth = getDepth( vUV );\n                \t\n                \tif( centerDepth >= ( 1.0 - EPSILON ) ) {\n                \t\tdiscard;\n                \t}\n\n                \tfloat centerViewZ = getViewZ( centerDepth );\n                \tvec3 viewPosition = getViewPos( vUV, centerDepth, centerViewZ );\n\n                \tfloat ambientOcclusion = getAmbientOcclusion( viewPosition );\n                \n                \tgl_FragColor = packFloatToRGBA(  1.0- ambientOcclusion );\n                }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const s=new Float32Array([1,1,0,1,0,0,1,0]),r=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),o=new Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ee(i,i.ARRAY_BUFFER,r,r.length,3,i.STATIC_DRAW),this._uvBuf=new ee(i,i.ARRAY_BUFFER,s,s.length,2,i.STATIC_DRAW),this._indicesBuf=new ee(i,i.ELEMENT_ARRAY_BUFFER,o,o.length,1,i.STATIC_DRAW),this._program.bind(),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uCameraProjectionMatrix=this._program.getLocation("uProjectMatrix"),this._uCameraInverseProjectionMatrix=this._program.getLocation("uInverseProjectMatrix"),this._uPerspective=this._program.getLocation("uPerspective"),this._uScale=this._program.getLocation("uScale"),this._uIntensity=this._program.getLocation("uIntensity"),this._uBias=this._program.getLocation("uBias"),this._uKernelRadius=this._program.getLocation("uKernelRadius"),this._uMinResolution=this._program.getLocation("uMinResolution"),this._uViewport=this._program.getLocation("uViewport"),this._uRandomSeed=this._program.getLocation("uRandomSeed"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV"),this._dirty=!1}destroy(){this._program&&(this._program.destroy(),this._program=null)}}const ne=new Float32Array(pe(17,[0,1])),le=new Float32Array(pe(17,[1,0])),he=new Float32Array(function(e,t){const i=[];for(let e=0;e<=17;e++)i.push(de(e,4));return i}()),ce=new Float32Array(2);class ue{constructor(e){this._scene=e,this._program=null,this._programError=!1,this._aPosition=null,this._aUV=null,this._uDepthTexture="uDepthTexture",this._uOcclusionTexture="uOcclusionTexture",this._uViewport=null,this._uCameraNear=null,this._uCameraFar=null,this._uCameraProjectionMatrix=null,this._uCameraInverseProjectionMatrix=null,this._uScale=null,this._uIntensity=null,this._uBias=null,this._uKernelRadius=null,this._uMinResolution=null,this._uvBuf=null,this._positionsBuf=null,this._indicesBuf=null,this.init()}init(){const e=this._scene.canvas.gl;if(this._program=new J(e,{vertex:["precision highp float;\n                precision highp int;\n                    \n                attribute vec3 aPosition;\n                attribute vec2 aUV;\n                uniform vec2 uViewport;\n                varying vec2 vUV;\n                varying vec2 vInvSize;\n                void main () {\n                    vUV = aUV;\n                    vInvSize = 1.0 / uViewport;\n                    gl_Position = vec4(aPosition, 1.0);\n                }"],fragment:["precision highp float;\n                precision highp int;\n                    \n                #define PI 3.14159265359\n                #define PI2 6.28318530718\n                #define EPSILON 1e-6\n\n                #define KERNEL_RADIUS 16\n\n                varying vec2        vUV;\n                varying vec2        vInvSize;\n            \n                uniform sampler2D   uDepthTexture;\n                uniform sampler2D   uOcclusionTexture;              \n               \n                uniform float       uCameraNear;\n                uniform float       uCameraFar;               \n                uniform float       uDepthCutoff;\n\n                uniform vec2        uSampleOffsets[ KERNEL_RADIUS + 1 ];\n                uniform float       uSampleWeights[ KERNEL_RADIUS + 1 ];\n\n                const float         unpackDownscale = 255. / 256.; \n\n                const vec3          packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );\n                const vec4          unpackFactors = unpackDownscale / vec4( packFactors, 1. );   \n\n                const float packUpscale = 256. / 255.;\n       \n                const float shiftRights = 1. / 256.;\n                \n                float unpackRGBAToFloat( const in vec4 v ) {\n                    return dot( floor( v * 255.0 + 0.5 ) / 255.0, unpackFactors );\n                }               \n\n                vec4 packFloatToRGBA( const in float v ) {\n                    vec4 r = vec4( fract( v * packFactors ), v );\n                    r.yzw -= r.xyz * shiftRights; \n                    return r * packUpscale;\n                }\n\n                float viewZToOrthographicDepth( const in float viewZ) {\n                    return ( viewZ + uCameraNear ) / ( uCameraNear - uCameraFar );\n                }\n              \n                float orthographicDepthToViewZ( const in float linearClipZ) {\n                    return linearClipZ * ( uCameraNear - uCameraFar ) - uCameraNear;\n                }\n\n                float viewZToPerspectiveDepth( const in float viewZ) {\n                    return (( uCameraNear + viewZ ) * uCameraFar ) / (( uCameraFar - uCameraNear ) * viewZ );\n                }\n                \n                float perspectiveDepthToViewZ( const in float invClipZ) {\n                    return ( uCameraNear * uCameraFar ) / ( ( uCameraFar - uCameraNear ) * invClipZ - uCameraFar );\n                }\n\n                float getDepth( const in vec2 screenPosition ) {"+(V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture?"return texture2D(uDepthTexture, screenPosition).r;":"return unpackRGBAToFloat(texture2D( uDepthTexture, screenPosition));")+"}\n\n                float getViewZ( const in float depth ) {\n                     return perspectiveDepthToViewZ( depth );\n                }\n\n                void main() {\n                \n                    float depth = getDepth( vUV );\n                    if( depth >= ( 1.0 - EPSILON ) ) {\n                        discard;\n                    }\n\n                    float centerViewZ = -getViewZ( depth );\n                    bool rBreak = false;\n                    bool lBreak = false;\n\n                    float weightSum = uSampleWeights[0];\n                    float occlusionSum = unpackRGBAToFloat(texture2D( uOcclusionTexture, vUV )) * weightSum;\n\n                    for( int i = 1; i <= KERNEL_RADIUS; i ++ ) {\n\n                        float sampleWeight = uSampleWeights[i];\n                        vec2 sampleUVOffset = uSampleOffsets[i] * vInvSize;\n\n                        vec2 sampleUV = vUV + sampleUVOffset;\n                        float viewZ = -getViewZ( getDepth( sampleUV ) );\n\n                        if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n                            rBreak = true;\n                        }\n\n                        if( ! rBreak ) {\n                            occlusionSum += unpackRGBAToFloat(texture2D( uOcclusionTexture, sampleUV )) * sampleWeight;\n                            weightSum += sampleWeight;\n                        }\n\n                        sampleUV = vUV - sampleUVOffset;\n                        viewZ = -getViewZ( getDepth( sampleUV ) );\n\n                        if( abs( viewZ - centerViewZ ) > uDepthCutoff ) {\n                            lBreak = true;\n                        }\n\n                        if( ! lBreak ) {\n                            occlusionSum += unpackRGBAToFloat(texture2D( uOcclusionTexture, sampleUV )) * sampleWeight;\n                            weightSum += sampleWeight;\n                        }\n                    }\n\n                    gl_FragColor = packFloatToRGBA(occlusionSum / weightSum);\n                }"]}),this._program.errors)return console.error(this._program.errors.join("\n")),void(this._programError=!0);const t=new Float32Array([1,1,0,1,0,0,1,0]),i=new Float32Array([1,1,0,-1,1,0,-1,-1,0,1,-1,0]),s=new Uint8Array([0,1,2,0,2,3]);this._positionsBuf=new ee(e,e.ARRAY_BUFFER,i,i.length,3,e.STATIC_DRAW),this._uvBuf=new ee(e,e.ARRAY_BUFFER,t,t.length,2,e.STATIC_DRAW),this._indicesBuf=new ee(e,e.ELEMENT_ARRAY_BUFFER,s,s.length,1,e.STATIC_DRAW),this._program.bind(),this._uViewport=this._program.getLocation("uViewport"),this._uCameraNear=this._program.getLocation("uCameraNear"),this._uCameraFar=this._program.getLocation("uCameraFar"),this._uDepthCutoff=this._program.getLocation("uDepthCutoff"),this._uSampleOffsets=e.getUniformLocation(this._program.handle,"uSampleOffsets"),this._uSampleWeights=e.getUniformLocation(this._program.handle,"uSampleWeights"),this._aPosition=this._program.getAttribute("aPosition"),this._aUV=this._program.getAttribute("aUV")}render(e,t,i){if(this._programError)return;this._getInverseProjectMat||(this._getInverseProjectMat=(()=>{let e=!0;this._scene.camera.on("projMatrix",(function(){e=!0}));const t=u.mat4();return()=>(e&&u.inverseMat4(o.camera.projMatrix,t),t)})());const s=this._scene.canvas.gl,r=this._program,o=this._scene,a=s.drawingBufferWidth,n=s.drawingBufferHeight,l=o.camera.project._state,h=l.near,c=l.far;s.viewport(0,0,a,n),s.clearColor(0,0,0,1),s.enable(s.DEPTH_TEST),s.disable(s.BLEND),s.frontFace(s.CCW),s.clear(s.COLOR_BUFFER_BIT|s.DEPTH_BUFFER_BIT),r.bind(),ce[0]=a,ce[1]=n,s.uniform2fv(this._uViewport,ce),s.uniform1f(this._uCameraNear,h),s.uniform1f(this._uCameraFar,c),s.uniform1f(this._uDepthCutoff,.01),0===i?s.uniform2fv(this._uSampleOffsets,le):s.uniform2fv(this._uSampleOffsets,ne),s.uniform1fv(this._uSampleWeights,he);const d=V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture?e.getDepthTexture():e.getTexture(),p=t.getTexture();r.bindTexture(this._uDepthTexture,d,0),r.bindTexture(this._uOcclusionTexture,p,1),this._aUV.bindArrayBuffer(this._uvBuf),this._aPosition.bindArrayBuffer(this._positionsBuf),this._indicesBuf.bind(),s.drawElements(s.TRIANGLES,this._indicesBuf.numItems,this._indicesBuf.itemType,0)}destroy(){this._program.destroy()}}function de(e,t){return Math.exp(-e*e/(t*t*2))/(Math.sqrt(2*Math.PI)*t)}function pe(e,t){const i=[];for(let s=0;s<=e;s++)i.push(t[0]*s),i.push(t[1]*s);return i}const _e=function(t,i){i=i||{};const s=new G(t),r=t.canvas.canvas,o=t.canvas.gl,a=!!i.transparent,n=i.alphaDepthMask,l=new e({});let h={},c={},p=!0,_=!0,f=!0;const g=new H(r,o,{depthTexture:V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture}),m=new H(r,o),v=new H(r,o),b=new H(r,o),P=new H(r,o);let y=!1;const M=new ae(t),x=new ue(t);function w(){p&&(function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],i=t.drawableMap,s=t.drawableListPreCull;let r=0;for(let e in i)i.hasOwnProperty(e)&&(s[r++]=i[e]);s.length=r}}(),p=!1,_=!0),_&&(function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e];t.isStateSortable&&t.drawableListPreCull.sort(t.stateSortCompare)}}(),_=!1,f=!0),f&&function(){for(let e in h)if(h.hasOwnProperty(e)){const t=h[e],i=t.drawableListPreCull,s=t.drawableList;let r=0;for(let e=0,t=i.length;e<t;e++){const t=i[e];t.rebuildRenderFlags(),t.renderFlags.culled||(s[r++]=t)}s.length=r}}()}function E(e){if(!e.castsShadow)return;const t=e.getShadowRenderBuf();if(t){t.bind(),s.reset(),s.backfaces=!0,s.frontface=!0,s.shadowViewMatrix=e.getShadowViewMatrix(),s.shadowProjMatrix=e.getShadowProjMatrix(),o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,1),o.enable(o.DEPTH_TEST),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];!1!==i.visible&&i.castsShadow&&i.drawShadow&&i.renderFlags.colorOpaque&&i.drawShadow(s)}}t.unbind()}}this._occlusionTester=null,this.needStateSort=function(){_=!0},this.shadowsDirty=function(){},this.imageDirty=function(){f=!0},this.webglContextLost=function(){},this.webglContextRestored=function(e){b.webglContextRestored(e),P.webglContextRestored(e),g.webglContextRestored(e),m.webglContextRestored(e),v.webglContextRestored(e),M.init(),x.init(),f=!0},this.addDrawable=function(e,t){const i=t.type;if(!i)return void console.error("Renderer#addDrawable() : drawable with ID "+e+" has no 'type' - ignoring");let s=h[i];s||(s={type:t.type,count:0,isStateSortable:t.isStateSortable,stateSortCompare:t.stateSortCompare,drawableMap:{},drawableListPreCull:[],drawableList:[]},h[i]=s),s.count++,s.drawableMap[e]=t,c[e]=t,p=!0},this.removeDrawable=function(e){const t=c[e];if(!t)return void console.error("Renderer#removeDrawable() : drawable not found with ID "+e+" - ignoring");const i=t.type,s=h[i];--s.count<=0?delete h[i]:delete s.drawableMap[e],delete c[e],p=!0},this.getPickID=function(e){return l.addItem(e)},this.putPickID=function(e){l.removeItem(e)},this.clear=function(e){if(o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),a)o.clearColor(1,1,1,1);else{const e=t.canvas.backgroundColorFromAmbientLight?this.lights.getAmbientColorAndIntensity():t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT)},this.render=function(e){(e=e||{}).force&&(f=!0),w(),f&&(function(e){V.SUPPORTED_EXTENSIONS.OES_element_index_uint&&o.getExtension("OES_element_index_uint"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.getExtension("EXT_frag_depth"),V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture&&o.getExtension("WEBGL_depth_texture"),t.sao.possible&&function(e){const i=t.sao;g.bind(),g.clear(),function(e){s.reset(),s.pass=e.pass,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),!1!==e.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];!0!==i.culled&&!1!==i.visible&&i.drawDepth&&i.renderFlags.colorOpaque&&i.drawDepth(s)}}}(e),g.unbind(),m.bind(),m.clear(),M.render(g),m.unbind(),i.blur&&(v.bind(),v.clear(),x.render(g,m,0),v.unbind(),m.bind(),m.clear(),x.render(g,v,1),m.unbind())}(e),function(){let e=t._lightsState.lights;for(let t=0,i=e.length;t<i;t++){const i=e[t];i.castsShadow&&E(i)}}(),A(e)}(e),d.frame.frameCount++,f=!1)};const A=function(){const e=[],i=[],r=[],l=[],c=[],u=[],p=[],_=[],f=[],g=[],v=[],b=[],P=[],y=[],M=[],x=[];return function(w){const E=t._lightsState.getAmbientColorAndIntensity();if(s.reset(),s.pass=w.pass,s.withSAO=!1,s.pbrEnabled=!!t.pbrEnabled,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),a)o.clearColor(0,0,0,0);else{const e=t.canvas.backgroundColorFromAmbientLight?E:t.canvas.backgroundColor;o.clearColor(e[0],e[1],e[2],1)}o.enable(o.DEPTH_TEST),o.frontFace(o.CCW),o.enable(o.CULL_FACE),o.depthMask(!0),o.lineWidth(1),s.lineWidth=1;const A=t.sao.possible;let C,S,D;s.occlusionTexture=A?m.getTexture():null;const L=Date.now();!1!==w.clear&&o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);let B=0,T=0,R=0,F=0,N=0,I=0,O=0,k=0,j=0,z=0,U=0,G=0,X=0,H=0,W=0,Y=0;for(let t in h)if(h.hasOwnProperty(t)){const o=h[t].drawableList;for(C=0,S=o.length;C<S;C++){if(D=o[C],!0===D.culled||!1===D.visible)continue;const t=D.renderFlags;t.colorOpaque&&(A&&D.saoEnabled?e[B++]=D:D.drawColorOpaque(s)),t.colorTransparent&&(r[R++]=D),t.xrayedSilhouetteTransparent&&(p[O++]=D),t.xrayedSilhouetteOpaque&&(c[N++]=D),t.highlightedSilhouetteTransparent&&(v[U++]=D),t.highlightedSilhouetteOpaque&&(f[j++]=D),t.selectedSilhouetteTransparent&&(M[W++]=D),t.selectedSilhouetteOpaque&&(P[X++]=D),t.edgesOpaque&&(i[T++]=D),t.edgesTransparent&&(l[F++]=D),t.selectedEdgesTransparent&&(x[Y++]=D),t.selectedEdgesOpaque&&(y[H++]=D),t.xrayedEdgesTransparent&&(_[k++]=D),t.xrayedEdgesOpaque&&(u[I++]=D),t.highlightedEdgesTransparent&&(b[G++]=D),t.highlightedEdgesOpaque&&(g[z++]=D)}}if(B>0)for(s.withSAO=!0,C=0;C<B;C++)e[C].drawColorOpaque(s);if(T>0)for(C=0;C<T;C++)i[C].drawEdgesColorOpaque(s);if(N>0)for(C=0;C<N;C++)c[C].drawSilhouetteXRayed(s);if(I>0)for(C=0;C<I;C++)u[C].drawEdgesXRayed(s);if(O>0||k>0||R>0||F>0){if(o.enable(o.CULL_FACE),o.enable(o.BLEND),a?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):(o.blendEquation(o.FUNC_ADD),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA)),s.backfaces=!1,n||o.depthMask(!1),k>0)for(C=0;C<k;C++)_[C].drawEdgesXRayed(s);if(O>0)for(C=0;C<O;C++)p[C].drawSilhouetteXRayed(s);if((R>0||F>0)&&o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),F>0)for(C=0;C<F;C++)D=l[C],D.drawEdgesColorTransparent(s);if(R>0)for(C=0;C<R;C++)D=r[C],D.drawColorTransparent(s);o.disable(o.BLEND),n||o.depthMask(!0)}if(j>0||z>0){if(s.lastProgramId=null,o.clear(o.DEPTH_BUFFER_BIT),z>0)for(C=0;C<z;C++)g[C].drawEdgesHighlighted(s);if(j>0)for(C=0;C<j;C++)f[C].drawSilhouetteHighlighted(s)}if(U>0||G>0||j>0){if(s.lastProgramId=null,o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),a?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),G>0)for(C=0;C<G;C++)b[C].drawEdgesHighlighted(s);if(U>0)for(C=0;C<U;C++)v[C].drawSilhouetteHighlighted(s);o.disable(o.BLEND)}if(X>0||H>0){if(s.lastProgramId=null,o.clear(o.DEPTH_BUFFER_BIT),H>0)for(C=0;C<H;C++)y[C].drawEdgesSelected(s);if(X>0)for(C=0;C<X;C++)P[C].drawSilhouetteSelected(s)}if(W>0||Y>0){if(s.lastProgramId=null,o.clear(o.DEPTH_BUFFER_BIT),o.enable(o.CULL_FACE),o.enable(o.BLEND),a?(o.blendEquation(o.FUNC_ADD),o.blendFuncSeparate(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA,o.ONE,o.ONE_MINUS_SRC_ALPHA)):o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),Y>0)for(C=0;C<Y;C++)x[C].drawEdgesSelected(s);if(W>0)for(C=0;C<W;C++)M[C].drawSilhouetteSelected(s);o.disable(o.BLEND)}const q=Date.now(),K=d.frame;K.renderTime=(q-L)/1e3,K.drawElements=s.drawElements,K.useProgram=s.useProgram,K.bindTexture=s.bindTexture,K.bindArray=s.bindArray;const Z=V.MAX_TEXTURE_UNITS;for(let e=0;e<Z;e++)o.activeTexture(o.TEXTURE0+e);o.bindTexture(o.TEXTURE_CUBE_MAP,null),o.bindTexture(o.TEXTURE_2D,null);const Q=V.MAX_VERTEX_ATTRIBS;for(let e=0;e<Q;e++)o.disableVertexAttribArray(e)}}();this.pick=function(){const e=u.vec3(),i=u.mat4(),a=u.mat4(),n=u.vec3([0,1,0]),c=new W,d=u.vec2();return function(p,_=c){let f,g,m,v,P;_.reset(),w(),V.SUPPORTED_EXTENSIONS.OES_element_index_uint&&o.getExtension("OES_element_index_uint"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.getExtension("EXT_frag_depth"),V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture&&o.getExtension("WEBGL_depth_texture");let y=null,M=null;if(_.pickSurface=p.pickSurface,p.canvasPos)f=p.canvasPos[0],g=p.canvasPos[1],y=t.camera.viewMatrix,M=t.camera.projMatrix,_.canvasPos=p.canvasPos;else{const s=u.frustumMat4(-1,1,-1,1,t.camera.project.near,t.camera.project.far,i);p.matrix?(y=p.matrix,M=s):(m=p.origin||u.vec3([0,0,0]),v=p.direction||u.vec3([0,0,1]),P=u.addVec3(m,v,e),y=u.lookAtMat4v(m,P,n,a),M=s,_.origin=m,_.direction=v),f=.5*r.clientWidth,g=.5*r.clientHeight}b.bind();const x=function(e,t,i,r,a){let n,c;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickViewMatrix=i,s.pickProjMatrix=r,s.pickInvisible=!!a.pickInvisible,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);const u=a.includeEntityIds,d=a.excludeEntityIds;for(let e in h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(n=0,c=t.length;n<c;n++){const e=t[n];!e.drawPickMesh||!0===e.culled||!0!==a.pickInvisible&&!1===e.visible||!1===e.pickable||u&&!u[e.id]||d&&d[e.id]||e.drawPickMesh(s)}}const p=b.read(Math.round(e),Math.round(t));let _=p[0]+256*p[1]+256*p[2]*256+256*p[3]*256*256;if(!(_<0))return l.items[_]}(f,g,y,M,p);if(!x)return b.unbind(),null;const E=x.delegatePickedEntity?x.delegatePickedEntity():x;return E?(p.pickSurface&&(x.canPickTriangle&&x.canPickTriangle()?(function(e,t,i,r,a,n){if(!e.drawPickTriangles)return;s.reset(),s.backfaces=!0,s.frontface=!0,s.pickViewMatrix=r,s.pickProjMatrix=a,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),e.drawPickTriangles(s);const l=b.read(t,i);let h=l[0]+256*l[1]+256*l[2]*256+256*l[3]*256*256;h*=3,n.primIndex=h}(x,f,g,y,M,_),x.pickTriangleSurface(y,M,_)):x.canPickWorldPos&&x.canPickWorldPos()&&(d[0]=t.camera.project.near,d[1]=t.camera.project.far,C(x,f,g,y,M,d,_),!1!==p.pickSurfaceNormal&&function(e,t,i,r,a,n,l){s.reset(),s.backfaces=!0,s.frontface=!0,s.pickViewMatrix=r,s.pickProjMatrix=a,s.pickZNear=n[0],s.pickZFar=n[1],o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),e.drawPickNormals(s);const h=b.read(Math.round(t),Math.round(i)),c=[h[0]/256-.5,h[1]/256-.5,h[2]/256-.5];u.normalizeVec3(c),l.worldNormal=c}(x,f,g,y,M,d,_))),b.unbind(),_.entity=E,_):null}}();const C=function(){const e=u.vec4(),t=u.vec4(),i=u.vec4(),a=u.vec4(),n=u.vec4(),l=u.mat4(),h=u.mat4(),c=u.mat4();return function(d,p,_,f,g,m,v){s.reset(),s.backfaces=!0,s.frontface=!0,s.pickViewMatrix=f,s.pickProjMatrix=g,s.pickZNear=m[0],s.pickZFar=m[1],o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT),d.drawPickDepths(s);const P=function(e){const t=[e[0]/256,e[1]/256,e[2]/256,e[3]/256];return u.dotVec4(t,[1/16777216,1/65536,1/256,1])}(b.read(Math.round(p),Math.round(_))),y=(p-r.width/2)/(r.width/2),M=-(_-r.height/2)/(r.height/2),x=d.rtcCenter;let w;if(x){const e=I(f,x,l);w=u.mulMat4(g,e,h)}else w=u.mulMat4(g,f,h);const E=u.inverseMat4(w,c);e[0]=y,e[1]=M,e[2]=-1,e[3]=1;let A=u.transformVec4(E,e);A=u.mulVec4Scalar(A,1/A[3]),t[0]=y,t[1]=M,t[2]=1,t[3]=1;let C=u.transformVec4(E,t);C=u.mulVec4Scalar(C,1/C[3]);const S=u.subVec3(C,A,i),D=u.addVec3(A,u.mulVec4Scalar(S,P,a),n);x&&u.addVec3(D,x),v.worldPos=D}}();this.addMarker=function(e){this._occlusionTester=this._occlusionTester||new re(t),this._occlusionTester.addMarker(e),t.occlusionTestCountdown=0},this.markerWorldPosUpdated=function(e){this._occlusionTester.markerWorldPosUpdated(e)},this.removeMarker=function(e){this._occlusionTester.removeMarker(e)},this.doOcclusionTest=function(){if(this._occlusionTester&&this._occlusionTester.needOcclusionTest){w(),this._occlusionTester.bindRenderBuf(),s.reset(),s.backfaces=!0,s.frontface=!0,o.viewport(0,0,o.drawingBufferWidth,o.drawingBufferHeight),o.clearColor(0,0,0,0),o.enable(o.DEPTH_TEST),o.disable(o.CULL_FACE),o.disable(o.BLEND),o.clear(o.COLOR_BUFFER_BIT|o.DEPTH_BUFFER_BIT);for(let e in h)if(h.hasOwnProperty(e)){const t=h[e].drawableList;for(let e=0,i=t.length;e<i;e++){const i=t[e];i.drawOcclusion&&!0!==i.culled&&!1!==i.visible&&!1!==i.pickable&&i.drawOcclusion(s)}}this._occlusionTester.drawMarkers(s),this._occlusionTester.doOcclusionTest(),this._occlusionTester.unbindRenderBuf()}},this.readPixels=function(e,t,i,s){let r,o,a,n;for(P.bind(),P.clear(),this.render({force:!0,opaqueOnly:s}),o=0;o<i;o++)a=2*o,n=4*o,r=P.read(e[a],e[a+1]),t[n]=r[0],t[n+1]=r[1],t[n+2]=r[2],t[n+3]=r[3];P.unbind(),f=!0},this.beginSnapshot=function(){P.bind(),P.clear(),y=!0},this.renderSnapshot=function(){y&&(P.clear(),this.render({force:!0,opaqueOnly:!1}),f=!0)},this.readSnapshot=function(e){return P.readImage(e)},this.endSnapshot=function(){y&&(P.unbind(),y=!1)},this.destroy=function(){h={},c={},b.destroy(),P.destroy(),g.destroy(),m.destroy(),v.destroy(),M.destroy(),x.destroy(),this._occlusionTester&&this._occlusionTester.destroy()}};class fe extends A{constructor(e,t={}){super(e,t),this.KEY_BACKSPACE=8,this.KEY_TAB=9,this.KEY_ENTER=13,this.KEY_SHIFT=16,this.KEY_CTRL=17,this.KEY_ALT=18,this.KEY_PAUSE_BREAK=19,this.KEY_CAPS_LOCK=20,this.KEY_ESCAPE=27,this.KEY_PAGE_UP=33,this.KEY_PAGE_DOWN=34,this.KEY_END=35,this.KEY_HOME=36,this.KEY_LEFT_ARROW=37,this.KEY_UP_ARROW=38,this.KEY_RIGHT_ARROW=39,this.KEY_DOWN_ARROW=40,this.KEY_INSERT=45,this.KEY_DELETE=46,this.KEY_NUM_0=48,this.KEY_NUM_1=49,this.KEY_NUM_2=50,this.KEY_NUM_3=51,this.KEY_NUM_4=52,this.KEY_NUM_5=53,this.KEY_NUM_6=54,this.KEY_NUM_7=55,this.KEY_NUM_8=56,this.KEY_NUM_9=57,this.KEY_A=65,this.KEY_B=66,this.KEY_C=67,this.KEY_D=68,this.KEY_E=69,this.KEY_F=70,this.KEY_G=71,this.KEY_H=72,this.KEY_I=73,this.KEY_J=74,this.KEY_K=75,this.KEY_L=76,this.KEY_M=77,this.KEY_N=78,this.KEY_O=79,this.KEY_P=80,this.KEY_Q=81,this.KEY_R=82,this.KEY_S=83,this.KEY_T=84,this.KEY_U=85,this.KEY_V=86,this.KEY_W=87,this.KEY_X=88,this.KEY_Y=89,this.KEY_Z=90,this.KEY_LEFT_WINDOW=91,this.KEY_RIGHT_WINDOW=92,this.KEY_SELECT_KEY=93,this.KEY_NUMPAD_0=96,this.KEY_NUMPAD_1=97,this.KEY_NUMPAD_2=98,this.KEY_NUMPAD_3=99,this.KEY_NUMPAD_4=100,this.KEY_NUMPAD_5=101,this.KEY_NUMPAD_6=102,this.KEY_NUMPAD_7=103,this.KEY_NUMPAD_8=104,this.KEY_NUMPAD_9=105,this.KEY_MULTIPLY=106,this.KEY_ADD=107,this.KEY_SUBTRACT=109,this.KEY_DECIMAL_POINT=110,this.KEY_DIVIDE=111,this.KEY_F1=112,this.KEY_F2=113,this.KEY_F3=114,this.KEY_F4=115,this.KEY_F5=116,this.KEY_F6=117,this.KEY_F7=118,this.KEY_F8=119,this.KEY_F9=120,this.KEY_F10=121,this.KEY_F11=122,this.KEY_F12=123,this.KEY_NUM_LOCK=144,this.KEY_SCROLL_LOCK=145,this.KEY_SEMI_COLON=186,this.KEY_EQUAL_SIGN=187,this.KEY_COMMA=188,this.KEY_DASH=189,this.KEY_PERIOD=190,this.KEY_FORWARD_SLASH=191,this.KEY_GRAVE_ACCENT=192,this.KEY_OPEN_BRACKET=219,this.KEY_BACK_SLASH=220,this.KEY_CLOSE_BRACKET=221,this.KEY_SINGLE_QUOTE=222,this.KEY_SPACE=32,this.element=t.element,this.altDown=!1,this.ctrlDown=!1,this.mouseDownLeft=!1,this.mouseDownMiddle=!1,this.mouseDownRight=!1,this.keyDown=[],this.enabled=!0,this.keyboardEnabled=!0,this.mouseover=!1,this.mouseCanvasPos=u.vec2(),this._bindEvents()}_bindEvents(){if(!this._eventsBound){document.addEventListener("keydown",this._keyDownListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!0:e.keyCode===this.KEY_ALT?this.altDown=!0:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!0),this.keyDown[e.keyCode]=!0,this.fire("keydown",e.keyCode,!0))},!1),document.addEventListener("keyup",this._keyUpListener=e=>{this.enabled&&this.keyboardEnabled&&"INPUT"!==e.target.tagName&&"TEXTAREA"!==e.target.tagName&&(e.keyCode===this.KEY_CTRL?this.ctrlDown=!1:e.keyCode===this.KEY_ALT?this.altDown=!1:e.keyCode===this.KEY_SHIFT&&(this.shiftDown=!1),this.keyDown[e.keyCode]=!1,this.fire("keyup",e.keyCode,!0))}),this.element.addEventListener("mouseenter",this._mouseEnterListener=e=>{this.enabled&&(this.mouseover=!0,this._getMouseCanvasPos(e),this.fire("mouseenter",this.mouseCanvasPos,!0))}),this.element.addEventListener("mouseleave",this._mouseLeaveListener=e=>{this.enabled&&(this.mouseover=!1,this._getMouseCanvasPos(e),this.fire("mouseleave",this.mouseCanvasPos,!0))}),this.element.addEventListener("mousedown",this._mouseDownListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!0;break;case 2:this.mouseDownMiddle=!0;break;case 3:this.mouseDownRight=!0}this._getMouseCanvasPos(e),this.element.focus(),this.fire("mousedown",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("mouseup",this._mouseUpListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownRight=!1}this.fire("mouseup",this.mouseCanvasPos,!0)}},!0),document.addEventListener("click",this._clickListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1}this._getMouseCanvasPos(e),this.fire("click",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),document.addEventListener("dblclick",this._dblClickListener=e=>{if(this.enabled){switch(e.which){case 1:this.mouseDownLeft=!1,this.mouseDownRight=!1;break;case 2:this.mouseDownMiddle=!1;break;case 3:this.mouseDownLeft=!1,this.mouseDownRight=!1}this._getMouseCanvasPos(e),this.fire("dblclick",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault()}}),this.element.addEventListener("mousemove",this._mouseMoveListener=e=>{this.enabled&&(this._getMouseCanvasPos(e),this.fire("mousemove",this.mouseCanvasPos,!0),this.mouseover&&e.preventDefault())}),this.element.addEventListener("wheel",this._mouseWheelListener=(e,t)=>{if(!this.enabled)return;const i=Math.max(-1,Math.min(1,40*-e.deltaY));this.fire("mousewheel",i,!0)},{passive:!0});{let e,t;const i=2;this.on("mousedown",(i=>{e=i[0],t=i[1]})),this.on("mouseup",(s=>{e>=s[0]-i&&e<=s[0]+i&&t>=s[1]-i&&t<=s[1]+i&&this.fire("mouseclicked",s,!0)}))}{const e={"landscape-primary":90,"landscape-secondary":-90,"portrait-secondary":180,"portrait-primary":0};let t,i;const s=u.vec3(),r=u.vec3(),o={orientation:null,orientationAngle:0},a={orientationAngle:0,acceleration:null,accelerationIncludingGravity:r,rotationRate:u.vec3(),interval:0},n={alpha:0,beta:0,gamma:0,absolute:!1};window.OrientationChangeEvent&&window.addEventListener("orientationchange",this._orientationchangedListener=()=>{t=window.screen.orientation||window.screen.mozOrientation||window.msOrientation||null,i=t&&e[t]||0,o.orientation=t,o.orientationAngle=i,this.fire("orientationchange",o)},!1),window.DeviceMotionEvent&&window.addEventListener("devicemotion",this._deviceMotionListener=e=>{a.interval=e.interval,a.orientationAngle=i;const t=e.acceleration;t?(s[0]=t.x,s[1]=t.y,s[2]=t.z,a.acceleration=s):a.acceleration=null;const o=e.accelerationIncludingGravity;o?(r[0]=o.x,r[1]=o.y,r[2]=o.z,a.accelerationIncludingGravity=r):a.accelerationIncludingGravity=null,a.rotationRate=e.rotationRate,this.fire("devicemotion",a)},!1),window.DeviceOrientationEvent&&window.addEventListener("deviceorientation",this._deviceOrientListener=e=>{n.gamma=e.gamma,n.beta=e.beta,n.alpha=e.alpha,n.absolute=e.absolute,this.fire("deviceorientation",n)},!1)}this._eventsBound=!0}}_unbindEvents(){this._eventsBound&&(document.removeEventListener("keydown",this._keyDownListener),document.removeEventListener("keyup",this._keyUpListener),this.element.removeEventListener("mouseenter",this._mouseEnterListener),this.element.removeEventListener("mouseleave",this._mouseLeaveListener),this.element.removeEventListener("mousedown",this._mouseDownListener),document.removeEventListener("mouseup",this._mouseDownListener),document.removeEventListener("click",this._clickListener),document.removeEventListener("dblclick",this._dblClickListener),this.element.removeEventListener("mousemove",this._mouseMoveListener),this.element.removeEventListener("wheel",this._mouseWheelListener),window.OrientationChangeEvent&&window.removeEventListener("orientationchange",this._orientationchangedListener),window.DeviceMotionEvent&&window.removeEventListener("devicemotion",this._deviceMotionListener),window.DeviceOrientationEvent&&window.removeEventListener("deviceorientation",this._deviceOrientListener),this._eventsBound=!1)}_getMouseCanvasPos(e){if(e){let t=e.target,i=0,s=0;for(;t.offsetParent;)i+=t.offsetLeft,s+=t.offsetTop,t=t.offsetParent;this.mouseCanvasPos[0]=e.pageX-i,this.mouseCanvasPos[1]=e.pageY-s}else e=window.event,this.mouseCanvasPos[0]=e.x,this.mouseCanvasPos[1]=e.y}setEnabled(e){this.enabled!==e&&this.fire("enabled",this.enabled=e)}getEnabled(){return this.enabled}setKeyboardEnabled(e){this.keyboardEnabled=e}getKeyboardEnabled(){return this.keyboardEnabled}destroy(){super.destroy(),this._unbindEvents()}}const ge=new e({});class me{constructor(e){this.id=ge.addItem({});for(const t in e)e.hasOwnProperty(t)&&(this[t]=e[t])}destroy(){ge.removeItem(this.id)}}class ve extends A{get type(){return"Viewport"}constructor(e,t={}){super(e,t),this._state=new me({boundary:[0,0,100,100]}),this.boundary=t.boundary,this.autoBoundary=t.autoBoundary}set boundary(e){if(!this._autoBoundary){if(!e){const t=this.scene.canvas.boundary;e=[0,0,t[2],t[3]]}this._state.boundary=e,this.glRedraw(),this.fire("boundary",this._state.boundary)}}get boundary(){return this._state.boundary}set autoBoundary(e){(e=!!e)!==this._autoBoundary&&(this._autoBoundary=e,this._autoBoundary?this._onCanvasSize=this.scene.canvas.on("boundary",(function(e){const t=e[2],i=e[3];this._state.boundary=[0,0,t,i],this.glRedraw(),this.fire("boundary",this._state.boundary)}),this):this._onCanvasSize&&(this.scene.canvas.off(this._onCanvasSize),this._onCanvasSize=null),this.fire("autoBoundary",this._autoBoundary))}get autoBoundary(){return this._autoBoundary}_getState(){return this._state}destroy(){super.destroy(),this._state.destroy()}}class be extends A{get type(){return"Perspective"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new me({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this._fov=60,this._canvasResized=this.scene.canvas.on("boundary",this._needUpdate,this),this.fov=t.fov,this.fovAxis=t.fovAxis,this.near=t.near,this.far=t.far}_update(){const e=this.scene.viewport.boundary,t=e[2]/e[3],i=this._fovAxis;let s=this._fov;("x"===i||"min"===i&&t<1||"max"===i&&t>1)&&(s/=t),s=Math.min(s,120),u.perspectiveMat4(s*(Math.PI/180),t,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set fov(e){(e=null!=e?e:60)!==this._fov&&(this._fov=e,this._needUpdate(0),this.fire("fov",this._fov))}get fov(){return this._fov}set fovAxis(e){e=e||"min",this._fovAxis!==e&&("x"!==e&&"y"!==e&&"min"!==e&&(this.error("Unsupported value for 'fovAxis': "+e+" - defaulting to 'min'"),e="min"),this._fovAxis=e,this._needUpdate(0),this.fire("fovAxis",this._fovAxis))}get fovAxis(){return this._fovAxis}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,a=o.offsetWidth/2,n=o.offsetHeight/2;return i[0]=(e[0]-a)/a,i[1]=(e[1]-n)/n,i[2]=t,i[3]=1,u.mulMat4v4(this.inverseMatrix,i,s),u.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._canvasResized)}}class Pe extends A{get type(){return"Ortho"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new me({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:2e3}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.scale=t.scale,this.near=t.near,this.far=t.far,this._onCanvasBoundary=this.scene.canvas.on("boundary",this._needUpdate,this)}_update(){const e=this.scene,t=.5*this._scale,i=e.viewport.boundary,s=i[2],r=i[3],o=s/r;let a,n,l,h;s>r?(a=-t,n=t,l=t/o,h=-t/o):(a=-t*o,n=t*o,l=t,h=-t),u.orthoMat4c(a,n,h,l,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set scale(e){null==e&&(e=1),e<=0&&(e=.01),this._scale=e,this._needUpdate(0),this.fire("scale",this._scale)}get scale(){return this._scale}set near(e){const t=null!=e?e:.1;this._state.near!==t&&(this._state.near=t,this._needUpdate(0),this.fire("near",this._state.near))}get near(){return this._state.near}set far(e){const t=null!=e?e:2e3;this._state.far!==t&&(this._state.far=t,this._needUpdate(0),this.fire("far",this._state.far))}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,a=o.offsetWidth/2,n=o.offsetHeight/2;return i[0]=(e[0]-a)/a,i[1]=(e[1]-n)/n,i[2]=t,i[3]=1,u.mulMat4v4(this.inverseMatrix,i,s),u.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),this.scene.canvas.off(this._onCanvasBoundary)}}class ye extends A{get type(){return"Frustum"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new me({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4(),near:.1,far:1e4}),this._left=-1,this._right=1,this._bottom=-1,this._top=1,this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.left=t.left,this.right=t.right,this.bottom=t.bottom,this.top=t.top,this.near=t.near,this.far=t.far}_update(){u.frustumMat4(this._left,this._right,this._bottom,this._top,this._state.near,this._state.far,this._state.matrix),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("matrix",this._state.matrix)}set left(e){this._left=null!=e?e:-1,this._needUpdate(0),this.fire("left",this._left)}get left(){return this._left}set right(e){this._right=null!=e?e:1,this._needUpdate(0),this.fire("right",this._right)}get right(){return this._right}set top(e){this._top=null!=e?e:1,this._needUpdate(0),this.fire("top",this._top)}get top(){return this._top}set bottom(e){this._bottom=null!=e?e:-1,this._needUpdate(0),this.fire("bottom",this._bottom)}get bottom(){return this._bottom}set near(e){this._state.near=null!=e?e:.1,this._needUpdate(0),this.fire("near",this._state.near)}get near(){return this._state.near}set far(e){this._state.far=null!=e?e:1e4,this._needUpdate(0),this.fire("far",this._state.far)}get far(){return this._state.far}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,a=o.offsetWidth/2,n=o.offsetHeight/2;return i[0]=(e[0]-a)/a,i[1]=(e[1]-n)/n,i[2]=t,i[3]=1,u.mulMat4v4(this.inverseMatrix,i,s),u.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy(),super.destroy()}}class Me extends A{get type(){return"CustomProjection"}constructor(e,t={}){super(e,t),this.camera=e,this._state=new me({matrix:u.mat4(),inverseMatrix:u.mat4(),transposedMatrix:u.mat4()}),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!1,this.matrix=t.matrix}set matrix(e){this._state.matrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._inverseMatrixDirty=!0,this._transposedMatrixDirty=!0,this.glRedraw(),this.fire("far",this._state.matrix)}get matrix(){return this._state.matrix}get inverseMatrix(){return this._updateScheduled&&this._doUpdate(),this._inverseMatrixDirty&&(u.inverseMat4(this._state.matrix,this._state.inverseMatrix),this._inverseMatrixDirty=!1),this._state.inverseMatrix}get transposedMatrix(){return this._updateScheduled&&this._doUpdate(),this._transposedMatrixDirty&&(u.transposeMat4(this._state.matrix,this._state.transposedMatrix),this._transposedMatrixDirty=!1),this._state.transposedMatrix}unproject(e,t,i,s,r){const o=this.scene.canvas.canvas,a=o.offsetWidth/2,n=o.offsetHeight/2;return i[0]=(e[0]-a)/a,i[1]=(e[1]-n)/n,i[2]=t,i[3]=1,u.mulMat4v4(this.inverseMatrix,i,s),u.mulVec3Scalar(s,1/s[3]),s[3]=1,s[1]*=-1,u.mulMat4v4(this.camera.inverseViewMatrix,s,r),r}destroy(){super.destroy(),this._state.destroy()}}const xe=u.vec3(),we=u.vec3(),Ee=u.vec3(),Ae=u.vec3(),Ce=u.vec3(),Se=u.vec3(),De=u.mat4(),Le=u.mat4(),Be=u.vec3(),Te=u.vec3(),Re=u.vec3(),Fe=u.vec3();class Ne extends A{get type(){return"Camera"}constructor(e,t={}){super(e,t),this._state=new me({deviceMatrix:u.mat4(),hasDeviceMatrix:!1,matrix:u.mat4(),normalMatrix:u.mat4(),inverseMatrix:u.mat4()}),this._perspective=new be(this),this._ortho=new Pe(this),this._frustum=new ye(this),this._customProjection=new Me(this),this._project=this._perspective,this._eye=u.vec3([0,0,10]),this._look=u.vec3([0,0,0]),this._up=u.vec3([0,1,0]),this._worldUp=u.vec3([0,1,0]),this._worldRight=u.vec3([1,0,0]),this._worldForward=u.vec3([0,0,-1]),this.deviceMatrix=t.deviceMatrix,this.eye=t.eye,this.look=t.look,this.up=t.up,this.worldAxis=t.worldAxis,this.gimbalLock=t.gimbalLock,this.constrainPitch=t.constrainPitch,this.projection=t.projection,this._perspective.on("matrix",(()=>{"perspective"===this._projectionType&&this.fire("projMatrix",this._perspective.matrix)})),this._ortho.on("matrix",(()=>{"ortho"===this._projectionType&&this.fire("projMatrix",this._ortho.matrix)})),this._frustum.on("matrix",(()=>{"frustum"===this._projectionType&&this.fire("projMatrix",this._frustum.matrix)})),this._customProjection.on("matrix",(()=>{"customProjection"===this._projectionType&&this.fire("projMatrix",this._customProjection.matrix)}))}_update(){const e=this._state;let t;"ortho"===this.projection?(u.subVec3(this._eye,this._look,Be),u.normalizeVec3(Be,Te),u.mulVec3Scalar(Te,1e3,Re),u.addVec3(this._look,Re,Fe),t=Fe):t=this._eye,e.hasDeviceMatrix?(u.lookAtMat4v(t,this._look,this._up,Le),u.mulMat4(e.deviceMatrix,Le,e.matrix)):u.lookAtMat4v(t,this._look,this._up,e.matrix),u.inverseMat4(this._state.matrix,this._state.inverseMatrix),u.transposeMat4(this._state.inverseMatrix,this._state.normalMatrix),this.glRedraw(),this.fire("matrix",this._state.matrix),this.fire("viewMatrix",this._state.matrix)}orbitYaw(e){let t=u.subVec3(this._eye,this._look,xe);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,De),t=u.transformPoint3(De,t,we),this.eye=u.addVec3(this._look,t,Ee),this.up=u.transformPoint3(De,this._up,Ae)}orbitPitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._eye,this._look,xe);const i=u.cross3Vec3(u.normalizeVec3(t,we),u.normalizeVec3(this._up,Ee));u.rotationMat4v(.0174532925*e,i,De),t=u.transformPoint3(De,t,Ae),this.up=u.transformPoint3(De,this._up,Ce),this.eye=u.addVec3(t,this._look,Se)}yaw(e){let t=u.subVec3(this._look,this._eye,xe);u.rotationMat4v(.0174532925*e,this._gimbalLock?this._worldUp:this._up,De),t=u.transformPoint3(De,t,we),this.look=u.addVec3(t,this._eye,Ee),this._gimbalLock&&(this.up=u.transformPoint3(De,this._up,Ae))}pitch(e){if(this._constrainPitch&&(e=u.dotVec3(this._up,this._worldUp)/u.DEGTORAD)<1)return;let t=u.subVec3(this._look,this._eye,xe);const i=u.cross3Vec3(u.normalizeVec3(t,we),u.normalizeVec3(this._up,Ee));u.rotationMat4v(.0174532925*e,i,De),this.up=u.transformPoint3(De,this._up,Se),t=u.transformPoint3(De,t,Ae),this.look=u.addVec3(t,this._eye,Ce)}pan(e){const t=u.subVec3(this._eye,this._look,xe),i=[0,0,0];let s;if(0!==e[0]){const r=u.cross3Vec3(u.normalizeVec3(t,[]),u.normalizeVec3(this._up,we));s=u.mulVec3Scalar(r,e[0]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]}0!==e[1]&&(s=u.mulVec3Scalar(u.normalizeVec3(this._up,Ee),e[1]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),0!==e[2]&&(s=u.mulVec3Scalar(u.normalizeVec3(t,Ae),e[2]),i[0]+=s[0],i[1]+=s[1],i[2]+=s[2]),this.eye=u.addVec3(this._eye,i,Ce),this.look=u.addVec3(this._look,i,Se)}zoom(e){const t=u.subVec3(this._eye,this._look,xe),i=Math.abs(u.lenVec3(t,we)),s=Math.abs(i+e);if(s<.5)return;const r=u.normalizeVec3(t,Ee);this.eye=u.addVec3(this._look,u.mulVec3Scalar(r,s),Ae)}set eye(e){this._eye.set(e||[0,0,10]),this._needUpdate(0),this.fire("eye",this._eye)}get eye(){return this._eye}set look(e){this._look.set(e||[0,0,0]),this._needUpdate(0),this.fire("look",this._look)}get look(){return this._look}set up(e){this._up.set(e||[0,1,0]),this._needUpdate(0),this.fire("up",this._up)}get up(){return this._up}set deviceMatrix(e){this._state.deviceMatrix.set(e||[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]),this._state.hasDeviceMatrix=!!e,this._needUpdate(0),this.fire("deviceMatrix",this._state.deviceMatrix)}get deviceMatrix(){return this._state.deviceMatrix}set worldAxis(e){e=e||[1,0,0,0,1,0,0,0,1],this._worldAxis?this._worldAxis.set(e):this._worldAxis=u.vec3(e),this._worldRight[0]=this._worldAxis[0],this._worldRight[1]=this._worldAxis[1],this._worldRight[2]=this._worldAxis[2],this._worldUp[0]=this._worldAxis[3],this._worldUp[1]=this._worldAxis[4],this._worldUp[2]=this._worldAxis[5],this._worldForward[0]=this._worldAxis[6],this._worldForward[1]=this._worldAxis[7],this._worldForward[2]=this._worldAxis[8],this.fire("worldAxis",this._worldAxis)}get worldAxis(){return this._worldAxis}get worldUp(){return this._worldUp}get xUp(){return this._worldUp[0]>this._worldUp[1]&&this._worldUp[0]>this._worldUp[2]}get yUp(){return this._worldUp[1]>this._worldUp[0]&&this._worldUp[1]>this._worldUp[2]}get zUp(){return this._worldUp[2]>this._worldUp[0]&&this._worldUp[2]>this._worldUp[1]}get worldRight(){return this._worldRight}get worldForward(){return this._worldForward}set gimbalLock(e){this._gimbalLock=!1!==e,this.fire("gimbalLock",this._gimbalLock)}get gimbalLock(){return this._gimbalLock}set constrainPitch(e){this._constrainPitch=!!e,this.fire("constrainPitch",this._constrainPitch)}get eyeLookDist(){return u.lenVec3(u.subVec3(this._look,this._eye,xe))}get matrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get viewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.matrix}get normalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get viewNormalMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.normalMatrix}get inverseViewMatrix(){return this._updateScheduled&&this._doUpdate(),this._state.inverseMatrix}get projMatrix(){return this[this.projection].matrix}get perspective(){return this._perspective}get ortho(){return this._ortho}get frustum(){return this._frustum}get customProjection(){return this._customProjection}set projection(e){e=e||"perspective",this._projectionType!==e&&("perspective"===e?this._project=this._perspective:"ortho"===e?this._project=this._ortho:"frustum"===e?this._project=this._frustum:"customProjection"===e?this._project=this._customProjection:(this.error("Unsupported value for 'projection': "+e+" defaulting to 'perspective'"),this._project=this._perspective,e="perspective"),this._project._update(),this._projectionType=e,this.glRedraw(),this._update(),this.fire("dirty"),this.fire("projection",this._projectionType),this.fire("projMatrix",this._project.matrix))}get projection(){return this._projectionType}get project(){return this._project}destroy(){super.destroy(),this._state.destroy()}}class Ie extends A{get type(){return"Light"}get isLight(){return!0}constructor(e,t={}){super(e,t)}}class Oe extends Ie{get type(){return"DirLight"}constructor(e,t={}){super(e,t),this._shadowRenderBuf=null,this._shadowViewMatrix=null,this._shadowProjMatrix=null,this._shadowViewMatrixDirty=!0,this._shadowProjMatrixDirty=!0;const i=this.scene.camera,s=this.scene.canvas;this._onCameraViewMatrix=i.on("viewMatrix",(()=>{this._shadowViewMatrixDirty=!0})),this._onCameraProjMatrix=i.on("projMatrix",(()=>{this._shadowProjMatrixDirty=!0})),this._onCanvasBoundary=s.on("boundary",(()=>{this._shadowProjMatrixDirty=!0})),this._state=new me({type:"dir",dir:u.vec3([1,1,1]),color:u.vec3([.7,.7,.8]),intensity:1,space:t.space||"view",castsShadow:!1,getShadowViewMatrix:()=>{if(this._shadowViewMatrixDirty){this._shadowViewMatrix||(this._shadowViewMatrix=u.identityMat4());const e=this.scene.camera,t=this._state.dir,i=e.look,s=[i[0]-t[0],i[1]-t[1],i[2]-t[2]],r=[0,1,0];u.lookAtMat4v(s,i,r,this._shadowViewMatrix),this._shadowViewMatrixDirty=!1}return this._shadowViewMatrix},getShadowProjMatrix:()=>(this._shadowProjMatrixDirty&&(this._shadowProjMatrix||(this._shadowProjMatrix=u.identityMat4()),u.orthoMat4c(-40,40,-40,40,-40,80,this._shadowProjMatrix),this._shadowProjMatrixDirty=!1),this._shadowProjMatrix),getShadowRenderBuf:()=>(this._shadowRenderBuf||(this._shadowRenderBuf=new H(this.scene.canvas.canvas,this.scene.canvas.gl,{size:[1024,1024]})),this._shadowRenderBuf)}),this.dir=t.dir,this.color=t.color,this.intensity=t.intensity,this.castsShadow=t.castsShadow,this.scene._lightCreated(this)}set dir(e){this._state.dir.set(e||[1,1,1]),this._shadowViewMatrixDirty=!0,this.glRedraw()}get dir(){return this._state.dir}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){e=void 0!==e?e:1,this._state.intensity=e,this.glRedraw()}get intensity(){return this._state.intensity}set castsShadow(e){e=!!e,this._state.castsShadow!==e&&(this._state.castsShadow=e,this._shadowViewMatrixDirty=!0,this.glRedraw())}get castsShadow(){return this._state.castsShadow}destroy(){const e=this.scene.camera,t=this.scene.canvas;e.off(this._onCameraViewMatrix),e.off(this._onCameraProjMatrix),t.off(this._onCanvasBoundary),super.destroy(),this._state.destroy(),this._shadowRenderBuf&&this._shadowRenderBuf.destroy(),this.scene._lightDestroyed(this),this.glRedraw()}}class ke extends Ie{get type(){return"AmbientLight"}constructor(e,t={}){super(e,t),this._state={type:"ambient",color:u.vec3([.7,.7,.7]),intensity:1},this.color=t.color,this.intensity=t.intensity,this.scene._lightCreated(this)}set color(e){this._state.color.set(e||[.7,.7,.8]),this.glRedraw()}get color(){return this._state.color}set intensity(e){this._state.intensity=void 0!==e?e:1,this.glRedraw()}get intensity(){return this._state.intensity}destroy(){super.destroy(),this.scene._lightDestroyed(this)}}class Ve extends A{get type(){return"Geometry"}get isGeometry(){return!0}constructor(e,t={}){super(e,t),d.memory.meshes++}destroy(){super.destroy(),d.memory.meshes--}}var je=function(){const e=[],t=[],i=[],s=[],r=[];let o=0;const a=new Uint16Array(3),n=new Uint16Array(3),l=new Uint16Array(3),h=u.vec3(),c=u.vec3(),d=u.vec3(),p=u.vec3(),_=u.vec3(),f=u.vec3(),g=u.vec3();return function(m,v,b,P){!function(r,o){const a={};let n,l,h,c;const u=Math.pow(10,4);let d,p,_=0;for(d=0,p=r.length;d<p;d+=3)n=r[d],l=r[d+1],h=r[d+2],c=Math.round(n*u)+"_"+Math.round(l*u)+"_"+Math.round(h*u),void 0===a[c]&&(a[c]=_/3,e[_++]=n,e[_++]=l,e[_++]=h),t[d/3]=a[c];for(d=0,p=o.length;d<p;d++)s[d]=t[o[d]],i[s[d]]=o[d]}(m,v),function(t,i){o=0;for(let m=0,v=t;m<v;m+=3){const t=3*s[m],v=3*s[m+1],b=3*s[m+2];i?(a[0]=e[t],a[1]=e[t+1],a[2]=e[t+2],n[0]=e[v],n[1]=e[v+1],n[2]=e[v+2],l[0]=e[b],l[1]=e[b+1],l[2]=e[b+2],u.decompressPosition(a,i,h),u.decompressPosition(n,i,c),u.decompressPosition(l,i,d)):(h[0]=e[t],h[1]=e[t+1],h[2]=e[t+2],c[0]=e[v],c[1]=e[v+1],c[2]=e[v+2],d[0]=e[b],d[1]=e[b+1],d[2]=e[b+2]),u.subVec3(d,c,p),u.subVec3(h,c,_),u.cross3Vec3(p,_,f),u.normalizeVec3(f,g);const P=r[o]||(r[o]={normal:u.vec3()});P.normal[0]=g[0],P.normal[1]=g[1],P.normal[2]=g[2],o++}}(v.length,b);const y=[],M=Math.cos(u.DEGTORAD*P),x={};let w,E,A,C,S,D,L,B,T,R,F,N=!1;for(let e=0,t=v.length;e<t;e+=3){const t=e/3;for(let i=0;i<3;i++)w=s[e+i],E=s[e+(i+1)%3],A=Math.min(w,E),C=Math.max(w,E),S=A+","+C,void 0===x[S]?x[S]={index1:A,index2:C,face1:t,face2:void 0}:x[S].face2=t}for(S in x)D=x[S],void 0!==D.face2&&(L=r[D.face1].normal,B=r[D.face2].normal,T=u.dotVec3(L,B),T>M)||(R=i[D.index1],F=i[D.index2],(!N&&R>65535||F>65535)&&(N=!0),y.push(R),y.push(F));return N?new Uint32Array(y):new Uint16Array(y)}}();function ze(e,t,i,s){let r=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),o=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){let e=(1-Math.abs(o))*(r>=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function Ue(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function Ge(e,t,i){return e[t]*i[0]+e[t+1]*i[1]+e[t+2]*i[2]}const Xe={getPositionsBounds:function(e){const t=new Float32Array(3),i=new Float32Array(3);let s,r;for(s=0;s<3;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=3)for(r=0;r<3;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},createPositionsDecodeMatrix:function(){const e=u.mat4(),t=u.mat4();return function(i,s){s=s||u.mat4();const r=i[0],o=i[1],a=i[2],n=i[3]-r,l=i[4]-o,h=i[5]-a,c=65535;return u.identityMat4(e),u.translationMat4v(i,e),u.identityMat4(t),u.scalingMat4v([n/c,l/c,h/c],t),u.mulMat4(e,t,s),s}}(),compressPositions:function(){const e=u.mat4(),t=u.mat4();return function(i,s,r){const o=new Uint16Array(i.length);var a=new Float32Array([r[0]!==s[0]?65535/(r[0]-s[0]):0,r[1]!==s[1]?65535/(r[1]-s[1]):0,r[2]!==s[2]?65535/(r[2]-s[2]):0]);let n;for(n=0;n<i.length;n+=3)o[n+0]=Math.floor((i[n+0]-s[0])*a[0]),o[n+1]=Math.floor((i[n+1]-s[1])*a[1]),o[n+2]=Math.floor((i[n+2]-s[2])*a[2]);return u.identityMat4(e),u.translationMat4v(s,e),u.identityMat4(t),u.scalingMat4v([(r[0]-s[0])/65535,(r[1]-s[1])/65535,(r[2]-s[2])/65535],t),{quantized:o,decodeMatrix:u.mulMat4(e,t,u.identityMat4())}}}(),decompressPositions:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[12],i[s+1]=e[s+1]*t[5]+t[13],i[s+2]=e[s+2]*t[10]+t[14];return i},decompressPosition:function(e,t,i){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i},decompressAABB:function(e,t,i=e){return i[0]=e[0]*t[0]+t[12],i[1]=e[1]*t[5]+t[13],i[2]=e[2]*t[10]+t[14],i[3]=e[3]*t[0]+t[12],i[4]=e[4]*t[5]+t[13],i[5]=e[5]*t[10]+t[14],i},getUVBounds:function(e){const t=new Float32Array(2),i=new Float32Array(2);let s,r;for(s=0;s<2;s++)t[s]=Number.MAX_VALUE,i[s]=-Number.MAX_VALUE;for(s=0;s<e.length;s+=2)for(r=0;r<2;r++)t[r]=Math.min(t[r],e[s+r]),i[r]=Math.max(i[r],e[s+r]);return{min:t,max:i}},compressUVs:function(){const e=u.mat3(),t=u.mat3();return function(i,s,r){const o=new Uint16Array(i.length),a=new Float32Array([65535/(r[0]-s[0]),65535/(r[1]-s[1])]);let n;for(n=0;n<i.length;n+=2)o[n+0]=Math.floor((i[n+0]-s[0])*a[0]),o[n+1]=Math.floor((i[n+1]-s[1])*a[1]);return u.identityMat3(e),u.translationMat3v(s,e),u.identityMat3(t),u.scalingMat3v([(r[0]-s[0])/65535,(r[1]-s[1])/65535],t),{quantized:o,decodeMatrix:u.mulMat3(e,t,u.identityMat3())}}}(),decompressUVs:function(e,t,i=new Float32Array(e.length)){for(let s=0,r=e.length;s<r;s+=3)i[s+0]=e[s+0]*t[0]+t[6],i[s+1]=e[s+1]*t[4]+t[7];return i},decompressUV:function(e,t,i){i[0]=e[0]*t[0]+t[6],i[1]=e[1]*t[4]+t[7]},compressNormals:function(e){const t=new Int8Array(e.length);let i,s,r,o,a;for(let n=0;n<e.length;n+=3)r=i=ze(e,n,"floor","floor"),s=Ue(i),o=a=Ge(e,n,s),i=ze(e,n,"ceil","floor"),s=Ue(i),o=Ge(e,n,s),o>a&&(r=i,a=o),i=ze(e,n,"floor","ceil"),s=Ue(i),o=Ge(e,n,s),o>a&&(r=i,a=o),i=ze(e,n,"ceil","ceil"),s=Ue(i),o=Ge(e,n,s),o>a&&(r=i,a=o),t[n]=r[0],t[n+1]=r[1];return t},decompressNormals:function(e,t){for(let i=0,s=0,r=e.length;i<r;i+=2){let r=e[i+0],o=e[i+1];r=(2*r+1)/255,o=(2*o+1)/255;const a=1-Math.abs(r)-Math.abs(o);a<0&&(r=(1-Math.abs(o))*(r>=0?1:-1),o=(1-Math.abs(r))*(o>=0?1:-1));const n=Math.sqrt(r*r+o*o+a*a);t[s+0]=r/n,t[s+1]=o/n,t[s+2]=a/n,s+=3}return t},decompressNormal:function(e,t){let i=e[0],s=e[1];i=(2*i+1)/255,s=(2*s+1)/255;const r=1-Math.abs(i)-Math.abs(s);r<0&&(i=(1-Math.abs(s))*(i>=0?1:-1),s=(1-Math.abs(i))*(s>=0?1:-1));const o=Math.sqrt(i*i+s*s+r*r);return t[0]=i/o,t[1]=s/o,t[2]=r/o,t}},He=d.memory,We=V.SUPPORTED_EXTENSIONS.OES_element_index_uint,Ye=We?Uint32Array:Uint16Array,qe=u.AABB3();class Ke extends Ve{get type(){return"ReadableGeometry"}get isReadableGeometry(){return!0}constructor(e,t={}){super(e,t),this._state=new me({compressGeometry:!!t.compressGeometry,primitive:null,primitiveName:null,positions:null,normals:null,colors:null,uv:null,indices:null,positionsDecodeMatrix:null,uvDecodeMatrix:null,positionsBuf:null,normalsBuf:null,colorsbuf:null,uvBuf:null,indicesBuf:null,hash:""}),this._numTriangles=0,this._edgeThreshold=t.edgeThreshold||10,this._edgeIndicesBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._aabbDirty=!0,this._boundingSphere=!0,this._aabb=null,this._aabbDirty=!0,this._obb=null,this._obbDirty=!0;const i=this._state,s=this.scene.canvas.gl;switch(t.primitive=t.primitive||"triangles",t.primitive){case"points":i.primitive=s.POINTS,i.primitiveName=t.primitive;break;case"lines":i.primitive=s.LINES,i.primitiveName=t.primitive;break;case"line-loop":i.primitive=s.LINE_LOOP,i.primitiveName=t.primitive;break;case"line-strip":i.primitive=s.LINE_STRIP,i.primitiveName=t.primitive;break;case"triangles":i.primitive=s.TRIANGLES,i.primitiveName=t.primitive;break;case"triangle-strip":i.primitive=s.TRIANGLE_STRIP,i.primitiveName=t.primitive;break;case"triangle-fan":i.primitive=s.TRIANGLE_FAN,i.primitiveName=t.primitive;break;default:this.error("Unsupported value for 'primitive': '"+t.primitive+"' - supported values are 'points', 'lines', 'line-loop', 'line-strip', 'triangles', 'triangle-strip' and 'triangle-fan'. Defaulting to 'triangles'."),i.primitive=s.TRIANGLES,i.primitiveName=t.primitive}if(t.positions)if(this._state.compressGeometry){const e=Xe.getPositionsBounds(t.positions),s=Xe.compressPositions(t.positions,e.min,e.max);i.positions=s.quantized,i.positionsDecodeMatrix=s.decodeMatrix}else i.positions=t.positions.constructor===Float32Array?t.positions:new Float32Array(t.positions);if(t.colors&&(i.colors=t.colors.constructor===Float32Array?t.colors:new Float32Array(t.colors)),t.uv)if(this._state.compressGeometry){const e=Xe.getUVBounds(t.uv),s=Xe.compressUVs(t.uv,e.min,e.max);i.uv=s.quantized,i.uvDecodeMatrix=s.decodeMatrix}else i.uv=t.uv.constructor===Float32Array?t.uv:new Float32Array(t.uv);if(t.normals&&(this._state.compressGeometry?i.normals=Xe.compressNormals(t.normals):i.normals=t.normals.constructor===Float32Array?t.normals:new Float32Array(t.normals)),t.indices){if(!We&&t.indices.constructor===Uint32Array)return void this.error("This WebGL implementation does not support Uint32Array");i.indices=t.indices.constructor===Uint32Array||t.indices.constructor===Uint16Array?t.indices:new Ye(t.indices),"triangles"===this._state.primitiveName&&(this._numTriangles=t.indices.length/3)}this._buildHash(),He.meshes++,this._buildVBOs()}_buildVBOs(){const e=this._state,t=this.scene.canvas.gl;if(e.indices&&(e.indicesBuf=new ee(t,t.ELEMENT_ARRAY_BUFFER,e.indices,e.indices.length,1,t.STATIC_DRAW),He.indices+=e.indicesBuf.numItems),e.positions&&(e.positionsBuf=new ee(t,t.ARRAY_BUFFER,e.positions,e.positions.length,3,t.STATIC_DRAW),He.positions+=e.positionsBuf.numItems),e.normals){let i=e.compressGeometry;e.normalsBuf=new ee(t,t.ARRAY_BUFFER,e.normals,e.normals.length,3,t.STATIC_DRAW,i),He.normals+=e.normalsBuf.numItems}e.colors&&(e.colorsBuf=new ee(t,t.ARRAY_BUFFER,e.colors,e.colors.length,4,t.STATIC_DRAW),He.colors+=e.colorsBuf.numItems),e.uv&&(e.uvBuf=new ee(t,t.ARRAY_BUFFER,e.uv,e.uv.length,2,t.STATIC_DRAW),He.uvs+=e.uvBuf.numItems)}_buildHash(){const e=this._state,t=["/g"];t.push("/"+e.primitive+";"),e.positions&&t.push("p"),e.colors&&t.push("c"),(e.normals||e.autoVertexNormals)&&t.push("n"),e.uv&&t.push("u"),e.compressGeometry&&t.push("cp"),t.push(";"),e.hash=t.join("")}_getEdgeIndices(){return this._edgeIndicesBuf||this._buildEdgeIndices(),this._edgeIndicesBuf}_getPickTrianglePositions(){return this._pickTrianglePositionsBuf||this._buildPickTriangleVBOs(),this._pickTrianglePositionsBuf}_getPickTriangleColors(){return this._pickTriangleColorsBuf||this._buildPickTriangleVBOs(),this._pickTriangleColorsBuf}_buildEdgeIndices(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=je(e.positions,e.indices,e.positionsDecodeMatrix,this._edgeThreshold);this._edgeIndicesBuf=new ee(t,t.ELEMENT_ARRAY_BUFFER,i,i.length,1,t.STATIC_DRAW),He.indices+=this._edgeIndicesBuf.numItems}_buildPickTriangleVBOs(){const e=this._state;if(!e.positions||!e.indices)return;const t=this.scene.canvas.gl,i=u.buildPickTriangles(e.positions,e.indices,e.compressGeometry),s=i.positions,r=i.colors;this._pickTrianglePositionsBuf=new ee(t,t.ARRAY_BUFFER,s,s.length,3,t.STATIC_DRAW),this._pickTriangleColorsBuf=new ee(t,t.ARRAY_BUFFER,r,r.length,4,t.STATIC_DRAW,!0),He.positions+=this._pickTrianglePositionsBuf.numItems,He.colors+=this._pickTriangleColorsBuf.numItems}_buildPickVertexVBOs(){}_webglContextLost(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextLost()}_webglContextRestored(){this._sceneVertexBufs&&this._sceneVertexBufs.webglContextRestored(),this._buildVBOs(),this._edgeIndicesBuf=null,this._pickVertexPositionsBuf=null,this._pickTrianglePositionsBuf=null,this._pickTriangleColorsBuf=null,this._pickVertexPositionsBuf=null,this._pickVertexColorsBuf=null}get primitive(){return this._state.primitiveName}get compressGeometry(){return this._state.compressGeometry}get positions(){return this._state.positions?this._state.compressGeometry?(this._decompressedPositions||(this._decompressedPositions=new Float32Array(this._state.positions.length),Xe.decompressPositions(this._state.positions,this._state.positionsDecodeMatrix,this._decompressedPositions)),this._decompressedPositions):this._state.positions:null}set positions(e){const t=this._state,i=t.positions;if(i)if(i.length===e.length){if(this._state.compressGeometry){const i=Xe.getPositionsBounds(e),s=Xe.compressPositions(e,i.min,i.max);e=s.quantized,t.positionsDecodeMatrix=s.decodeMatrix}i.set(e),t.positionsBuf&&t.positionsBuf.setData(i),this._setAABBDirty(),this.glRedraw()}else this.error("can't update geometry positions - new positions are wrong length");else this.error("can't update geometry positions - geometry has no positions")}get normals(){if(this._state.normals){if(!this._state.compressGeometry)return this._state.normals;if(!this._decompressedNormals){const e=this._state.normals.length,t=e+e/2;this._decompressedNormals=new Float32Array(t),Xe.decompressNormals(this._state.normals,this._decompressedNormals)}return this._decompressedNormals}}set normals(e){if(this._state.compressGeometry)return void this.error("can't update geometry normals - quantized geometry is immutable");const t=this._state,i=t.normals;i?i.length===e.length?(i.set(e),t.normalsBuf&&t.normalsBuf.setData(i),this.glRedraw()):this.error("can't update geometry normals - new normals are wrong length"):this.error("can't update geometry normals - geometry has no normals")}get uv(){return this._state.uv?this._state.compressGeometry?(this._decompressedUV||(this._decompressedUV=new Float32Array(this._state.uv.length),Xe.decompressUVs(this._state.uv,this._state.uvDecodeMatrix,this._decompressedUV)),this._decompressedUV):this._state.uv:null}set uv(e){if(this._state.compressGeometry)return void this.error("can't update geometry UVs - quantized geometry is immutable");const t=this._state,i=t.uv;i?i.length===e.length?(i.set(e),t.uvBuf&&t.uvBuf.setData(i),this.glRedraw()):this.error("can't update geometry UVs - new UVs are wrong length"):this.error("can't update geometry UVs - geometry has no UVs")}get colors(){return this._state.colors}set colors(e){if(this._state.compressGeometry)return void this.error("can't update geometry colors - quantized geometry is immutable");const t=this._state,i=t.colors;i?i.length===e.length?(i.set(e),t.colorsBuf&&t.colorsBuf.setData(i),this.glRedraw()):this.error("can't update geometry colors - new colors are wrong length"):this.error("can't update geometry colors - geometry has no colors")}get indices(){return this._state.indices}get aabb(){return this._aabbDirty&&(this._aabb||(this._aabb=u.AABB3()),u.positions3ToAABB3(this._state.positions,this._aabb,this._state.positionsDecodeMatrix),this._aabbDirty=!1),this._aabb}get obb(){return this._obbDirty&&(this._obb||(this._obb=u.OBB3()),u.positions3ToAABB3(this._state.positions,qe,this._state.positionsDecodeMatrix),u.AABB3ToOBB3(qe,this._obb),this._obbDirty=!1),this._obb}get numTriangles(){return this._numTriangles}_setAABBDirty(){this._aabbDirty||(this._aabbDirty=!0,this._aabbDirty=!0,this._obbDirty=!0)}_getState(){return this._state}destroy(){super.destroy();const e=this._state;e.indicesBuf&&e.indicesBuf.destroy(),e.positionsBuf&&e.positionsBuf.destroy(),e.normalsBuf&&e.normalsBuf.destroy(),e.uvBuf&&e.uvBuf.destroy(),e.colorsBuf&&e.colorsBuf.destroy(),this._edgeIndicesBuf&&this._edgeIndicesBuf.destroy(),this._pickTrianglePositionsBuf&&this._pickTrianglePositionsBuf.destroy(),this._pickTriangleColorsBuf&&this._pickTriangleColorsBuf.destroy(),this._pickVertexPositionsBuf&&this._pickVertexPositionsBuf.destroy(),this._pickVertexColorsBuf&&this._pickVertexColorsBuf.destroy(),e.destroy(),He.meshes--}}function Ze(e={}){let t=e.xSize||1;t<0&&(console.error("negative xSize not allowed - will invert"),t*=-1);let i=e.ySize||1;i<0&&(console.error("negative ySize not allowed - will invert"),i*=-1);let s=e.zSize||1;s<0&&(console.error("negative zSize not allowed - will invert"),s*=-1);const r=e.center,o=r?r[0]:0,a=r?r[1]:0,n=r?r[2]:0,l=-t+o,h=-i+a,c=-s+n,u=t+o,d=i+a,p=s+n;return f.apply(e,{positions:[u,d,p,l,d,p,l,h,p,u,h,p,u,d,p,u,h,p,u,h,c,u,d,c,u,d,p,u,d,c,l,d,c,l,d,p,l,d,p,l,d,c,l,h,c,l,h,p,l,h,c,u,h,c,u,h,p,l,h,p,u,h,c,l,h,c,l,d,c,u,d,c],normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],uv:[1,0,0,0,0,1,1,1,0,0,0,1,1,1,1,0,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]})}class Qe extends A{get type(){return"Material"}constructor(e,t={}){super(e,t),d.memory.materials++}destroy(){super.destroy(),d.memory.materials--}}const $e={opaque:0,mask:1,blend:2},Je=["opaque","mask","blend"];class et extends Qe{get type(){return"PhongMaterial"}constructor(e,t={}){super(e,t),this._state=new me({type:"PhongMaterial",ambient:u.vec3([1,1,1]),diffuse:u.vec3([1,1,1]),specular:u.vec3([1,1,1]),emissive:u.vec3([0,0,0]),alpha:null,shininess:null,reflectivity:null,alphaMode:null,alphaCutoff:null,lineWidth:null,pointSize:null,backfaces:null,frontface:null,hash:null}),this.ambient=t.ambient,this.diffuse=t.diffuse,this.specular=t.specular,this.emissive=t.emissive,this.alpha=t.alpha,this.shininess=t.shininess,this.reflectivity=t.reflectivity,this.lineWidth=t.lineWidth,this.pointSize=t.pointSize,t.ambientMap&&(this._ambientMap=this._checkComponent("Texture",t.ambientMap)),t.diffuseMap&&(this._diffuseMap=this._checkComponent("Texture",t.diffuseMap)),t.specularMap&&(this._specularMap=this._checkComponent("Texture",t.specularMap)),t.emissiveMap&&(this._emissiveMap=this._checkComponent("Texture",t.emissiveMap)),t.alphaMap&&(this._alphaMap=this._checkComponent("Texture",t.alphaMap)),t.reflectivityMap&&(this._reflectivityMap=this._checkComponent("Texture",t.reflectivityMap)),t.normalMap&&(this._normalMap=this._checkComponent("Texture",t.normalMap)),t.occlusionMap&&(this._occlusionMap=this._checkComponent("Texture",t.occlusionMap)),t.diffuseFresnel&&(this._diffuseFresnel=this._checkComponent("Fresnel",t.diffuseFresnel)),t.specularFresnel&&(this._specularFresnel=this._checkComponent("Fresnel",t.specularFresnel)),t.emissiveFresnel&&(this._emissiveFresnel=this._checkComponent("Fresnel",t.emissiveFresnel)),t.alphaFresnel&&(this._alphaFresnel=this._checkComponent("Fresnel",t.alphaFresnel)),t.reflectivityFresnel&&(this._reflectivityFresnel=this._checkComponent("Fresnel",t.reflectivityFresnel)),this.alphaMode=t.alphaMode,this.alphaCutoff=t.alphaCutoff,this.backfaces=t.backfaces,this.frontface=t.frontface,this._makeHash()}_makeHash(){const e=this._state,t=["/p"];this._normalMap&&(t.push("/nm"),this._normalMap.hasMatrix&&t.push("/mat")),this._ambientMap&&(t.push("/am"),this._ambientMap.hasMatrix&&t.push("/mat"),t.push("/"+this._ambientMap.encoding)),this._diffuseMap&&(t.push("/dm"),this._diffuseMap.hasMatrix&&t.push("/mat"),t.push("/"+this._diffuseMap.encoding)),this._specularMap&&(t.push("/sm"),this._specularMap.hasMatrix&&t.push("/mat")),this._emissiveMap&&(t.push("/em"),this._emissiveMap.hasMatrix&&t.push("/mat"),t.push("/"+this._emissiveMap.encoding)),this._alphaMap&&(t.push("/opm"),this._alphaMap.hasMatrix&&t.push("/mat")),this._reflectivityMap&&(t.push("/rm"),this._reflectivityMap.hasMatrix&&t.push("/mat")),this._occlusionMap&&(t.push("/ocm"),this._occlusionMap.hasMatrix&&t.push("/mat")),this._diffuseFresnel&&t.push("/df"),this._specularFresnel&&t.push("/sf"),this._emissiveFresnel&&t.push("/ef"),this._alphaFresnel&&t.push("/of"),this._reflectivityFresnel&&t.push("/rf"),t.push(";"),e.hash=t.join("")}set ambient(e){let t=this._state.ambient;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.ambient=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get ambient(){return this._state.ambient}set diffuse(e){let t=this._state.diffuse;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.diffuse=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get diffuse(){return this._state.diffuse}set specular(e){let t=this._state.specular;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.specular=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1),this.glRedraw()}get specular(){return this._state.specular}set emissive(e){let t=this._state.emissive;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.emissive=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=0,t[1]=0,t[2]=0),this.glRedraw()}get emissive(){return this._state.emissive}set alpha(e){e=null!=e?e:1,this._state.alpha!==e&&(this._state.alpha=e,this.glRedraw())}get alpha(){return this._state.alpha}set shininess(e){this._state.shininess=void 0!==e?e:80,this.glRedraw()}get shininess(){return this._state.shininess}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set pointSize(e){this._state.pointSize=e||1,this.glRedraw()}get pointSize(){return this._state.pointSize}set reflectivity(e){this._state.reflectivity=void 0!==e?e:1,this.glRedraw()}get reflectivity(){return this._state.reflectivity}get normalMap(){return this._normalMap}get ambientMap(){return this._ambientMap}get diffuseMap(){return this._diffuseMap}get specularMap(){return this._specularMap}get emissiveMap(){return this._emissiveMap}get alphaMap(){return this._alphaMap}get reflectivityMap(){return this._reflectivityMap}get occlusionMap(){return this._occlusionMap}get diffuseFresnel(){return this._diffuseFresnel}get specularFresnel(){return this._specularFresnel}get emissiveFresnel(){return this._emissiveFresnel}get alphaFresnel(){return this._alphaFresnel}get reflectivityFresnel(){return this._reflectivityFresnel}set alphaMode(e){let t=$e[e=e||"opaque"];void 0===t&&(this.error("Unsupported value for 'alphaMode': "+e+" - defaulting to 'opaque'"),t="opaque"),this._state.alphaMode!==t&&(this._state.alphaMode=t,this.glRedraw())}get alphaMode(){return Je[this._state.alphaMode]}set alphaCutoff(e){null==e&&(e=.5),this._state.alphaCutoff!==e&&(this._state.alphaCutoff=e)}get alphaCutoff(){return this._state.alphaCutoff}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set frontface(e){e="cw"!==e,this._state.frontface!==e&&(this._state.frontface=e,this.glRedraw())}get frontface(){return this._state.frontface?"ccw":"cw"}destroy(){super.destroy(),this._state.destroy()}}const tt={default:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultWhiteBG:{fill:!0,fillColor:[1,1,1],fillAlpha:.6,edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.2,.2,.2],edgeAlpha:.5,edgeWidth:1},defaultDarkBG:{fill:!0,fillColor:[.4,.4,.4],fillAlpha:.2,edges:!0,edgeColor:[.5,.5,.5],edgeAlpha:.5,edgeWidth:1},phosphorous:{fill:!0,fillColor:[0,0,0],fillAlpha:.4,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:2},sunset:{fill:!0,fillColor:[.9,.9,.6],fillAlpha:.2,edges:!0,edgeColor:[.9,.9,.9],edgeAlpha:.5,edgeWidth:1},vectorscope:{fill:!0,fillColor:[0,0,0],fillAlpha:.7,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:2},battlezone:{fill:!0,fillColor:[0,0,0],fillAlpha:1,edges:!0,edgeColor:[.2,1,.2],edgeAlpha:1,edgeWidth:3},sepia:{fill:!0,fillColor:[.970588207244873,.7965892553329468,.6660899519920349],fillAlpha:.4,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},yellowHighlight:{fill:!0,fillColor:[1,1,0],fillAlpha:.5,edges:!0,edgeColor:[.529411792755127,.4577854573726654,.4100345969200134],edgeAlpha:1,edgeWidth:1},greenSelected:{fill:!0,fillColor:[0,1,0],fillAlpha:.5,edges:!0,edgeColor:[.4577854573726654,.529411792755127,.4100345969200134],edgeAlpha:1,edgeWidth:1},gamegrid:{fill:!0,fillColor:[.2,.2,.7],fillAlpha:.9,edges:!0,edgeColor:[.4,.4,1.6],edgeAlpha:.8,edgeWidth:3}};class it extends Qe{get type(){return"EmphasisMaterial"}get presets(){return tt}constructor(e,t={}){super(e,t),this._state=new me({type:"EmphasisMaterial",fill:null,fillColor:null,fillAlpha:null,edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null,backfaces:!0}),this._preset="default",t.preset?(this.preset=t.preset,void 0!==t.fill&&(this.fill=t.fill),t.fillColor&&(this.fillColor=t.fillColor),void 0!==t.fillAlpha&&(this.fillAlpha=t.fillAlpha),void 0!==t.edges&&(this.edges=t.edges),t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth),void 0!==t.backfaces&&(this.backfaces=t.backfaces)):(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this.backfaces=t.backfaces)}set fill(e){e=!1!==e,this._state.fill!==e&&(this._state.fill=e,this.glRedraw())}get fill(){return this._state.fill}set fillColor(e){let t=this._state.fillColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.fillColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.4,t[1]=.4,t[2]=.4),this.glRedraw()}get fillColor(){return this._state.fillColor}set fillAlpha(e){e=null!=e?e:.2,this._state.fillAlpha!==e&&(this._state.fillAlpha=e,this.glRedraw())}get fillAlpha(){return this._state.fillAlpha}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:.5,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set backfaces(e){e=!!e,this._state.backfaces!==e&&(this._state.backfaces=e,this.glRedraw())}get backfaces(){return this._state.backfaces}set preset(e){if(e=e||"default",this._preset===e)return;const t=tt[e];t?(this.fill=t.fill,this.fillColor=t.fillColor,this.fillAlpha=t.fillAlpha,this.edges=t.edges,this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(tt).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const st={default:{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1},defaultWhiteBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultLightBG:{edgeColor:[.2,.2,.2],edgeAlpha:1,edgeWidth:1},defaultDarkBG:{edgeColor:[.5,.5,.5],edgeAlpha:1,edgeWidth:1}};class rt extends Qe{get type(){return"EdgeMaterial"}get presets(){return st}constructor(e,t={}){super(e,t),this._state=new me({type:"EdgeMaterial",edges:null,edgeColor:null,edgeAlpha:null,edgeWidth:null}),this._preset="default",t.preset?(this.preset=t.preset,t.edgeColor&&(this.edgeColor=t.edgeColor),void 0!==t.edgeAlpha&&(this.edgeAlpha=t.edgeAlpha),void 0!==t.edgeWidth&&(this.edgeWidth=t.edgeWidth)):(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth),this.edges=!1!==t.edges}set edges(e){e=!1!==e,this._state.edges!==e&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set edgeColor(e){let t=this._state.edgeColor;if(t){if(e&&t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2])return}else t=this._state.edgeColor=new Float32Array(3);e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=.2,t[1]=.2,t[2]=.2),this.glRedraw()}get edgeColor(){return this._state.edgeColor}set edgeAlpha(e){e=null!=e?e:1,this._state.edgeAlpha!==e&&(this._state.edgeAlpha=e,this.glRedraw())}get edgeAlpha(){return this._state.edgeAlpha}set edgeWidth(e){this._state.edgeWidth=e||1,this.glRedraw()}get edgeWidth(){return this._state.edgeWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=st[e];t?(this.edgeColor=t.edgeColor,this.edgeAlpha=t.edgeAlpha,this.edgeWidth=t.edgeWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(st).join(", "))}get preset(){return this._preset}destroy(){super.destroy(),this._state.destroy()}}const ot={meters:{abbrev:"m"},metres:{abbrev:"m"},centimeters:{abbrev:"cm"},centimetres:{abbrev:"cm"},millimeters:{abbrev:"mm"},millimetres:{abbrev:"mm"},yards:{abbrev:"yd"},feet:{abbrev:"ft"},inches:{abbrev:"in"}};class at extends A{constructor(e,t={}){super(e,t),this._units="meters",this._scale=1,this._origin=u.vec3([0,0,0]),this.units=t.units,this.scale=t.scale,this.origin=t.origin}get unitsInfo(){return ot}set units(e){e||(e="meters"),ot[e]||(this.error("Unsupported value for 'units': "+e+" defaulting to 'meters'"),e="meters"),this._units=e,this.fire("units",this._units)}get units(){return this._units}set scale(e){(e=e||1)<=0?this.error("scale value should be larger than zero"):(this._scale=e,this.fire("scale",this._scale))}get scale(){return this._scale}set origin(e){if(!e)return this._origin[0]=0,this._origin[1]=0,void(this._origin[2]=0);this._origin[0]=e[0],this._origin[1]=e[1],this._origin[2]=e[2],this.fire("origin",this._origin)}get origin(){return this._origin}worldToRealPos(e,t=u.vec3(3)){t[0]=this._origin[0]+this._scale*e[0],t[1]=this._origin[1]+this._scale*e[1],t[2]=this._origin[2]+this._scale*e[2]}realToWorldPos(e,t=u.vec3(3)){return t[0]=(e[0]-this._origin[0])/this._scale,t[1]=(e[1]-this._origin[1])/this._scale,t[2]=(e[2]-this._origin[2])/this._scale,t}}class nt extends A{constructor(e,t={}){super(e,t);const i=navigator.userAgent.match(/(opera|chrome|safari|firefox|msie)\/?\s*(\.?\d+(\.\d+)*)/i),s="safari"===(navigator.userAgent.match(/Edge/i)||navigator.userAgent.match(/Trident.*rv[ :]*11\./i)?"msie":i[1].toLowerCase());this._supported=!s&&V.SUPPORTED_EXTENSIONS.OES_standard_derivatives,this.enabled=t.enabled,this.kernelRadius=t.kernelRadius,this.intensity=t.intensity,this.bias=t.bias,this.scale=t.scale,this.minResolution=t.minResolution,this.numSamples=t.numSamples,this.blur=t.blur,this.blendCutoff=t.blendCutoff,this.blendFactor=t.blendFactor}get supported(){return this._supported}set enabled(e){e=!!e,this._enabled!==e&&(this._enabled=e,this.glRedraw())}get enabled(){return this._enabled}get possible(){if(!this._supported)return!1;if(!this._enabled)return!1;const e=this.scene.camera.projection;return"customProjection"!==e&&"frustum"!==e}get active(){return this._active}set kernelRadius(e){null==e&&(e=100),this._kernelRadius!==e&&(this._kernelRadius=e,this.glRedraw())}get kernelRadius(){return this._kernelRadius}set intensity(e){null==e&&(e=.15),this._intensity!==e&&(this._intensity=e,this.glRedraw())}get intensity(){return this._intensity}set bias(e){null==e&&(e=.5),this._bias!==e&&(this._bias=e,this.glRedraw())}get bias(){return this._bias}set scale(e){null==e&&(e=1),this._scale!==e&&(this._scale=e,this.glRedraw())}get scale(){return this._scale}set minResolution(e){null==e&&(e=0),this._minResolution!==e&&(this._minResolution=e,this.glRedraw())}get minResolution(){return this._minResolution}set numSamples(e){null==e&&(e=10),this._numSamples!==e&&(this._numSamples=e,this.glRedraw())}get numSamples(){return this._numSamples}set blur(e){e=!1!==e,this._blur!==e&&(this._blur=e,this.glRedraw())}get blur(){return this._blur}set blendCutoff(e){null==e&&(e=.3),this._blendCutoff!==e&&(this._blendCutoff=e,this.glRedraw())}get blendCutoff(){return this._blendCutoff}set blendFactor(e){null==e&&(e=1),this._blendFactor!==e&&(this._blendFactor=e,this.glRedraw())}get blendFactor(){return this._blendFactor}destroy(){super.destroy()}}const lt={default:{pointSize:4,roundPoints:!0,perspectivePoints:!0},square:{pointSize:4,roundPoints:!1,perspectivePoints:!0},round:{pointSize:4,roundPoints:!0,perspectivePoints:!0}};class ht extends Qe{get type(){return"PointsMaterial"}get presets(){return lt}constructor(e,t={}){super(e,t),this._state=new me({type:"PointsMaterial",pointSize:null,roundPoints:null,perspectivePoints:null,minPerspectivePointSize:null,maxPerspectivePointSize:null}),t.preset?(this.preset=t.preset,void 0!==t.pointSize&&(this.pointSize=t.pointSize),void 0!==t.roundPoints&&(this.roundPoints=t.roundPoints),void 0!==t.perspectivePoints&&(this.perspectivePoints=t.perspectivePoints),void 0!==t.minPerspectivePointSize&&(this.minPerspectivePointSize=t.minPerspectivePointSize),void 0!==t.maxPerspectivePointSize&&(this.maxPerspectivePointSize=t.minPerspectivePointSize)):(this._preset="default",this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize)}set pointSize(e){this._state.pointSize=e||2,this.glRedraw()}get pointSize(){return this._state.pointSize}set roundPoints(e){e=!1!==e,this._state.roundPoints!==e&&(this._state.roundPoints=e,this.scene._needRecompile=!0,this.glRedraw())}get roundPoints(){return this._state.roundPoints}set perspectivePoints(e){e=!1!==e,this._state.perspectivePoints!==e&&(this._state.perspectivePoints=e,this.scene._needRecompile=!0,this.glRedraw())}get perspectivePoints(){return this._state.perspectivePoints}set minPerspectivePointSize(e){this._state.minPerspectivePointSize=e||1,this.scene._needRecompile=!0,this.glRedraw()}get minPerspectivePointSize(){return this._state.minPerspectivePointSize}set maxPerspectivePointSize(e){this._state.maxPerspectivePointSize=e||6,this.scene._needRecompile=!0,this.glRedraw()}get maxPerspectivePointSize(){return this._state.maxPerspectivePointSize}set preset(e){if(e=e||"default",this._preset===e)return;const t=lt[e];t?(this.pointSize=t.pointSize,this.roundPoints=t.roundPoints,this.perspectivePoints=t.perspectivePoints,this.minPerspectivePointSize=t.minPerspectivePointSize,this.maxPerspectivePointSize=t.maxPerspectivePointSize,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(lt).join(", "))}get preset(){return this._preset}get hash(){return[this.pointSize,this.roundPoints,this.perspectivePoints,this.minPerspectivePointSize,this.maxPerspectivePointSize].join(";")}destroy(){super.destroy(),this._state.destroy()}}const ct={default:{lineWidth:1},thick:{lineWidth:2},thicker:{lineWidth:4}};class ut extends Qe{get type(){return"LinesMaterial"}get presets(){return ct}constructor(e,t={}){super(e,t),this._state=new me({type:"LinesMaterial",lineWidth:null}),t.preset?(this.preset=t.preset,void 0!==t.lineWidth&&(this.lineWidth=t.lineWidth)):(this._preset="default",this.lineWidth=t.lineWidth)}set lineWidth(e){this._state.lineWidth=e||1,this.glRedraw()}get lineWidth(){return this._state.lineWidth}set preset(e){if(e=e||"default",this._preset===e)return;const t=ct[e];t?(this.lineWidth=t.lineWidth,this._preset=e):this.error("unsupported preset: '"+e+"' - supported values are "+Object.keys(ct).join(", "))}get preset(){return this._preset}get hash(){return[""+this.lineWidth].join(";")}destroy(){super.destroy(),this._state.destroy()}}function dt(e,t){const i={};let s,r;for(let o=0,a=t.length;o<a;o++)s=t[o],r=e.component[s],r?r.isEntity?i[s]=!0:e.warn("pick(): Component is not an Entity: "+s):e.warn("pick(): Component not found: "+s);return i}class pt extends A{get type(){return"Scene"}constructor(e,t={}){super(null,t);const i=t.canvasElement||document.getElementById(t.canvasId);if(!(i instanceof HTMLCanvasElement))throw"Mandatory config expected: valid canvasId or canvasElement";const s=!!t.transparent,r=!!t.alphaDepthMask;this._aabbDirty=!0,this.viewer=e,this.occlusionTestCountdown=0,this.loading=0,this.startTime=(new Date).getTime(),this.models={},this.objects={},this._numObjects=0,this.visibleObjects={},this._numVisibleObjects=0,this.xrayedObjects={},this._numXRayedObjects=0,this.highlightedObjects={},this._numHighlightedObjects=0,this.selectedObjects={},this._numSelectedObjects=0,this.colorizedObjects={},this._numColorizedObjects=0,this.opacityObjects={},this._numOpacityObjects=0,this.offsetObjects={},this._numOffsetObjects=0,this._modelIds=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this._opacityObjectIds=null,this._offsetObjectIds=null,this._collidables={},this._compilables={},this._needRecompile=!1,this.types={},this.components={},this.sectionPlanes={},this.lights={},this.lightMaps={},this.reflectionMaps={},this.realWorldOffset=t.realWorldOffset||new Float64Array([0,0,0]),this.canvas=new U(this,{dontClear:!0,canvas:i,spinnerElementId:t.spinnerElementId,transparent:s,webgl2:!1!==t.webgl2,contextAttr:t.contextAttr||{},backgroundColor:t.backgroundColor,backgroundColorFromAmbientLight:t.backgroundColorFromAmbientLight,premultipliedAlpha:t.premultipliedAlpha}),this.canvas.on("boundary",(()=>{this.glRedraw()})),this.canvas.on("webglContextFailed",(()=>{alert("xeokit failed to find WebGL!")})),this._renderer=new _e(this,{transparent:s,alphaDepthMask:r}),this._sectionPlanesState=new function(){this.sectionPlanes=[],this.clippingCaps=!1;let e=null;this.getHash=function(){if(e)return e;const t=this.sectionPlanes;if(0===t.length)return this.hash=";";const i=[];for(let e=0,s=t.length;e<s;e++)t[e],i.push("cp");return i.push(";"),e=i.join(""),e},this.addSectionPlane=function(t){this.sectionPlanes.push(t),e=null},this.removeSectionPlane=function(t){for(let i=0,s=this.sectionPlanes.length;i<s;i++)if(this.sectionPlanes[i].id===t.id)return this.sectionPlanes.splice(i,1),void(e=null)}},this._lightsState=new function(){const e=u.vec4([0,0,0,0]),t=u.vec4();this.lights=[],this.reflectionMaps=[],this.lightMaps=[];let i=null,s=null;this.getHash=function(){if(i)return i;const e=[],t=this.lights;let s;for(let i=0,r=t.length;i<r;i++)s=t[i],e.push("/"),e.push(s.type),e.push("world"===s.space?"w":"v"),s.castsShadow&&e.push("sh");return this.lightMaps.length>0&&e.push("/lm"),this.reflectionMaps.length>0&&e.push("/rm"),e.push(";"),i=e.join(""),i},this.addLight=function(e){this.lights.push(e),s=null,i=null},this.removeLight=function(e){for(let t=0,r=this.lights.length;t<r;t++)if(this.lights[t].id===e.id)return this.lights.splice(t,1),s&&s.id===e.id&&(s=null),void(i=null)},this.addReflectionMap=function(e){this.reflectionMaps.push(e),i=null},this.removeReflectionMap=function(e){for(let t=0,s=this.reflectionMaps.length;t<s;t++)if(this.reflectionMaps[t].id===e.id)return this.reflectionMaps.splice(t,1),void(i=null)},this.addLightMap=function(e){this.lightMaps.push(e),i=null},this.removeLightMap=function(e){for(let t=0,s=this.lightMaps.length;t<s;t++)if(this.lightMaps[t].id===e.id)return this.lightMaps.splice(t,1),void(i=null)},this.getAmbientColorAndIntensity=function(){if(!s)for(let e=0,t=this.lights.length;e<t;e++){const t=this.lights[e];if("ambient"===t.type){s=t;break}}if(s){const e=s.color,i=s.intensity;return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=i,t}return e}},this.input=new fe(this,{dontClear:!0,element:this.canvas.canvas}),this.metrics=new at(this,{units:t.units,scale:t.scale,origin:t.origin}),this.sao=new nt(this,{enabled:t.saoEnabled}),this.ticksPerRender=t.ticksPerRender,this.ticksPerOcclusionTest=t.ticksPerOcclusionTest,this.passes=t.passes,this.clearEachPass=t.clearEachPass,this.gammaInput=t.gammaInput,this.gammaOutput=t.gammaOutput,this.gammaFactor=t.gammaFactor,this._entityOffsetsEnabled=!!t.entityOffsetsEnabled,this._logarithmicDepthBufferEnabled=!!t.logarithmicDepthBufferEnabled,this._pbrEnabled=!!t.pbrEnabled,w._addScene(this),this._initDefaults(),this._viewport=new ve(this,{id:"default.viewport",autoBoundary:!0,dontClear:!0}),this._camera=new Ne(this,{id:"default.camera",dontClear:!0}),new ke(this,{color:[1,1,1],intensity:.7}),new Oe(this,{dir:[.8,-.5,-.5],color:[.67,.67,1],intensity:.7,space:"world"}),new Oe(this,{dir:[-.8,-1,.5],color:[1,1,.9],intensity:.9,space:"world"}),this._camera.on("dirty",(()=>{this._renderer.imageDirty()}))}_initDefaults(){this.geometry,this.material,this.xrayMaterial,this.edgeMaterial,this.selectedMaterial,this.highlightMaterial}_addComponent(e){if(e.id&&this.components[e.id]&&(this.error("Component "+f.inQuotes(e.id)+" already exists in Scene - ignoring ID, will randomly-generate instead"),e.id=null),!e.id)for(void 0===window.nextID&&(window.nextID=0),e.id="__"+window.nextID++;this.components[e.id];)e.id=u.createUUID();this.components[e.id]=e;const t=e.type;let i=this.types[e.type];i||(i=this.types[t]={}),i[e.id]=e,e.compile&&(this._compilables[e.id]=e),e.isDrawable&&(this._renderer.addDrawable(e.id,e),this._collidables[e.id]=e)}_removeComponent(e){var t=e.id,i=e.type;delete this.components[t];const s=this.types[i];s&&(delete s[t],f.isEmptyObject(s)&&delete this.types[i]),e.compile&&delete this._compilables[e.id],e.isDrawable&&(this._renderer.removeDrawable(e.id),delete this._collidables[e.id])}_sectionPlaneCreated(e){this.sectionPlanes[e.id]=e,this.scene._sectionPlanesState.addSectionPlane(e._state),this.scene.fire("sectionPlaneCreated",e,!0),this._needRecompile=!0}_lightCreated(e){this.lights[e.id]=e,this.scene._lightsState.addLight(e._state),this._needRecompile=!0}_lightMapCreated(e){this.lightMaps[e.id]=e,this.scene._lightsState.addLightMap(e._state),this._needRecompile=!0}_reflectionMapCreated(e){this.reflectionMaps[e.id]=e,this.scene._lightsState.addReflectionMap(e._state),this._needRecompile=!0}_sectionPlaneDestroyed(e){delete this.sectionPlanes[e.id],this.scene._sectionPlanesState.removeSectionPlane(e._state),this.scene.fire("sectionPlaneDestroyed",e,!0),this._needRecompile=!0}_lightDestroyed(e){delete this.lights[e.id],this.scene._lightsState.removeLight(e._state),this._needRecompile=!0}_lightMapDestroyed(e){delete this.lightMaps[e.id],this.scene._lightsState.removeLightMap(e._state),this._needRecompile=!0}_reflectionMapDestroyed(e){delete this.reflectionMaps[e.id],this.scene._lightsState.removeReflectionMap(e._state),this._needRecompile=!0}_registerModel(e){this.models[e.id]=e,this._modelIds=null}_deregisterModel(e){delete this.models[e.id],this._modelIds=null}_registerObject(e){this.objects[e.id]=e,this._numObjects++,this._objectIds=null}_deregisterObject(e){delete this.objects[e.id],this._numObjects--,this._objectIds=null}_objectVisibilityUpdated(e,t=!0){e.visible?(this.visibleObjects[e.id]=e,this._numVisibleObjects++):(delete this.visibleObjects[e.id],this._numVisibleObjects--),this._visibleObjectIds=null,t&&this.fire("objectVisibility",e,!0)}_objectXRayedUpdated(e){e.xrayed?(this.xrayedObjects[e.id]=e,this._numXRayedObjects++):(delete this.xrayedObjects[e.id],this._numXRayedObjects--),this._xrayedObjectIds=null}_objectHighlightedUpdated(e){e.highlighted?(this.highlightedObjects[e.id]=e,this._numHighlightedObjects++):(delete this.highlightedObjects[e.id],this._numHighlightedObjects--),this._highlightedObjectIds=null}_objectSelectedUpdated(e){e.selected?(this.selectedObjects[e.id]=e,this._numSelectedObjects++):(delete this.selectedObjects[e.id],this._numSelectedObjects--),this._selectedObjectIds=null}_objectColorizeUpdated(e,t){t?(this.colorizedObjects[e.id]=e,this._numColorizedObjects++):(delete this.colorizedObjects[e.id],this._numColorizedObjects--),this._colorizedObjectIds=null}_objectOpacityUpdated(e,t){t?(this.opacityObjects[e.id]=e,this._numOpacityObjects++):(delete this.opacityObjects[e.id],this._numOpacityObjects--),this._opacityObjectIds=null}_objectOffsetUpdated(e,t){!t||0===t[0]&&0===t[1]&&0===t[2]?(this.offsetObjects[e.id]=e,this._numOffsetObjects++):(delete this.offsetObjects[e.id],this._numOffsetObjects--),this._offsetObjectIds=null}_webglContextLost(){this.canvas.spinner.processes++;for(const e in this.components)if(this.components.hasOwnProperty(e)){const t=this.components[e];t._webglContextLost&&t._webglContextLost()}this._renderer.webglContextLost()}_webglContextRestored(){const e=this.canvas.gl;for(const t in this.components)if(this.components.hasOwnProperty(t)){const i=this.components[t];i._webglContextRestored&&i._webglContextRestored(e)}this._renderer.webglContextRestored(e),this.canvas.spinner.processes--}get entityOffsetsEnabled(){return this._entityOffsetsEnabled}get logarithmicDepthBufferEnabled(){return this._logarithmicDepthBufferEnabled}set pbrEnabled(e){this._pbrEnabled=!!e,this.glRedraw()}get pbrEnabled(){return this._pbrEnabled}doOcclusionTest(){this._needRecompile&&(this._recompile(),this._needRecompile=!1),this._renderer.doOcclusionTest()}render(e){e&&w.runTasks();const t={sceneId:null,pass:0};this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),t.sceneId=this.id;const i=this._passes,s=this._clearEachPass;let r,o;for(r=0;r<i;r++)t.pass=r,this.fire("rendering",t,!0),o=s||0===r,this._renderer.render({pass:r,clear:o,force:e}),this.fire("rendered",t,!0);this._saveAmbientColor()}_recompile(){for(const e in this._compilables)this._compilables.hasOwnProperty(e)&&this._compilables[e].compile();this._renderer.shadowsDirty(),this.fire("compile",this,!0)}_saveAmbientColor(){const e=this.canvas;if(e.transparent||e.backgroundImage||e.backgroundColor)this._lastAmbientColor=null;else{const t=this._lightsState.getAmbientColorAndIntensity();this._lastAmbientColor&&this._lastAmbientColor[0]===t[0]&&this._lastAmbientColor[1]===t[1]&&this._lastAmbientColor[2]===t[2]&&this._lastAmbientColor[3]===t[3]||(e.backgroundColor=t,this._lastAmbientColor||(this._lastAmbientColor=u.vec4([0,0,0,1])),this._lastAmbientColor.set(t))}}get modelIds(){return this._modelIds||(this._modelIds=Object.keys(this.models)),this._modelIds}get numObjects(){return this._numObjects}get objectIds(){return this._objectIds||(this._objectIds=Object.keys(this.objects)),this._objectIds}get numVisibleObjects(){return this._numVisibleObjects}get visibleObjectIds(){return this._visibleObjectIds||(this._visibleObjectIds=Object.keys(this.visibleObjects)),this._visibleObjectIds}get numXRayedObjects(){return this._numXRayedObjects}get xrayedObjectIds(){return this._xrayedObjectIds||(this._xrayedObjectIds=Object.keys(this.xrayedObjects)),this._xrayedObjectIds}get numHighlightedObjects(){return this._numHighlightedObjects}get highlightedObjectIds(){return this._highlightedObjectIds||(this._highlightedObjectIds=Object.keys(this.highlightedObjects)),this._highlightedObjectIds}get numSelectedObjects(){return this._numSelectedObjects}get selectedObjectIds(){return this._selectedObjectIds||(this._selectedObjectIds=Object.keys(this.selectedObjects)),this._selectedObjectIds}get numColorizedObjects(){return this._numColorizedObjects}get colorizedObjectIds(){return this._colorizedObjectIds||(this._colorizedObjectIds=Object.keys(this.colorizedObjects)),this._colorizedObjectIds}get opacityObjectIds(){return this._opacityObjectIds||(this._opacityObjectIds=Object.keys(this.opacityObjects)),this._opacityObjectIds}get offsetObjectIds(){return this._offsetObjectIds||(this._offsetObjectIds=Object.keys(this.offsetObjects)),this._offsetObjectIds}set ticksPerRender(e){null==e?e=1:(!f.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerRender': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._ticksPerRender&&(this._ticksPerRender=e)}get ticksPerRender(){return this._ticksPerRender}set ticksPerOcclusionTest(e){null==e?e=20:(!f.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'ticksPerOcclusionTest': '"+e+"' - should be an integer greater than zero."),e=20),e!==this._ticksPerOcclusionTest&&(this._ticksPerOcclusionTest=e)}get ticksPerOcclusionTest(){return this._ticksPerOcclusionTest}set passes(e){null==e?e=1:(!f.isNumeric(e)||e<=0)&&(this.error("Unsupported value for 'passes': '"+e+"' - should be an integer greater than zero."),e=1),e!==this._passes&&(this._passes=e,this.glRedraw())}get passes(){return this._passes}set clearEachPass(e){(e=!!e)!==this._clearEachPass&&(this._clearEachPass=e,this.glRedraw())}get clearEachPass(){return this._clearEachPass}set gammaInput(e){(e=!1!==e)!==this._renderer.gammaInput&&(this._renderer.gammaInput=e,this._needRecompile=!0,this.glRedraw())}get gammaInput(){return this._renderer.gammaInput}set gammaOutput(e){(e=!!e)!==this._renderer.gammaOutput&&(this._renderer.gammaOutput=e,this._needRecompile=!0,this.glRedraw())}get gammaOutput(){return this._renderer.gammaOutput}set gammaFactor(e){(e=null==e?2.2:e)!==this._renderer.gammaFactor&&(this._renderer.gammaFactor=e,this.glRedraw())}get gammaFactor(){return this._renderer.gammaFactor}get geometry(){return this.components["default.geometry"]||Ze(Ke)}get material(){return this.components["default.material"]||new et(this,{id:"default.material",emissive:[.4,.4,.4],dontClear:!0})}get xrayMaterial(){return this.components["default.xrayMaterial"]||new it(this,{id:"default.xrayMaterial",preset:"sepia",dontClear:!0})}get highlightMaterial(){return this.components["default.highlightMaterial"]||new it(this,{id:"default.highlightMaterial",preset:"yellowHighlight",dontClear:!0})}get selectedMaterial(){return this.components["default.selectedMaterial"]||new it(this,{id:"default.selectedMaterial",preset:"greenSelected",dontClear:!0})}get edgeMaterial(){return this.components["default.edgeMaterial"]||new rt(this,{id:"default.edgeMaterial",preset:"default",edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1,dontClear:!0})}get pointsMaterial(){return this.components["default.pointsMaterial"]||new ht(this,{id:"default.pointsMaterial",preset:"default",dontClear:!0})}get linesMaterial(){return this.components["default.linesMaterial"]||new ut(this,{id:"default.linesMaterial",preset:"default",dontClear:!0})}get viewport(){return this._viewport}get camera(){return this._camera}get center(){if(this._aabbDirty||!this._center){this._center&&this._center||(this._center=u.vec3());const e=this.aabb;this._center[0]=(e[0]+e[3])/2,this._center[1]=(e[1]+e[4])/2,this._center[2]=(e[2]+e[5])/2}return this._center}get aabb(){if(this._aabbDirty){this._aabb||(this._aabb=u.AABB3());let e,t=u.MAX_DOUBLE,i=u.MAX_DOUBLE,s=u.MAX_DOUBLE,r=u.MIN_DOUBLE,o=u.MIN_DOUBLE,a=u.MIN_DOUBLE;const n=this._collidables;let l,h=!1;for(const c in n)if(n.hasOwnProperty(c)){if(l=n[c],!1===l.collidable)continue;e=l.aabb,e[0]<t&&(t=e[0]),e[1]<i&&(i=e[1]),e[2]<s&&(s=e[2]),e[3]>r&&(r=e[3]),e[4]>o&&(o=e[4]),e[5]>a&&(a=e[5]),h=!0}h||(t=-100,i=-100,s=-100,r=100,o=100,a=100),this._aabb[0]=t,this._aabb[1]=i,this._aabb[2]=s,this._aabb[3]=r,this._aabb[4]=o,this._aabb[5]=a,this._aabbDirty=!1}return this._aabb}_setAABBDirty(){this._aabbDirty=!0,this.fire("boundary")}pick(e,t){if(0===this.canvas.boundary[2]||0===this.canvas.boundary[3])return this.error("Picking not allowed while canvas has zero width or height"),null;(e=e||{}).pickSurface=e.pickSurface||e.rayPick,e.canvasPos||e.matrix||e.origin&&e.direction||this.warn("picking without canvasPos, matrix, or ray origin and direction");const i=e.includeEntities||e.include;i&&(e.includeEntityIds=dt(this,i));const s=e.excludeEntities||e.exclude;return s&&(e.excludeEntityIds=dt(this,s)),this._needRecompile&&(this._recompile(),this._renderer.imageDirty(),this._needRecompile=!1),(t=this._renderer.pick(e,t))?(t.entity&&t.entity.fire&&t.entity.fire("picked",t),t):void 0}clear(){var e;for(const t in this.components)this.components.hasOwnProperty(t)&&((e=this.components[t])._dontClear||e.destroy())}clearLights(){const e=Object.keys(this.lights);for(let t=0,i=e.length;t<i;t++)this.lights[e[t]].destroy()}clearSectionPlanes(){const e=Object.keys(this.sectionPlanes);for(let t=0,i=e.length;t<i;t++)this.sectionPlanes[e[t]].destroy()}getAABB(e){if(void 0===e)return this.aabb;if(f.isString(e)){const t=this.objects[e];if(t&&t.aabb)return t.aabb;e=[e]}if(0===e.length)return this.aabb;let t,i=u.MAX_DOUBLE,s=u.MAX_DOUBLE,r=u.MAX_DOUBLE,o=u.MIN_DOUBLE,a=u.MIN_DOUBLE,n=u.MIN_DOUBLE;if(this.withObjects(e,(e=>{if(e.collidable){const l=e.aabb;l[0]<i&&(i=l[0]),l[1]<s&&(s=l[1]),l[2]<r&&(r=l[2]),l[3]>o&&(o=l[3]),l[4]>a&&(a=l[4]),l[5]>n&&(n=l[5]),t=!0}})),t){const e=u.AABB3();return e[0]=i,e[1]=s,e[2]=r,e[3]=o,e[4]=a,e[5]=n,e}return this.aabb}setObjectsVisible(e,t){return this.withObjects(e,(e=>{const i=e.visible!==t;return e.visible=t,i}))}setObjectsCollidable(e,t){return this.withObjects(e,(e=>{const i=e.collidable!==t;return e.collidable=t,i}))}setObjectsCulled(e,t){return this.withObjects(e,this.objects,(e=>{const i=e.culled!==t;return e.culled=t,i}))}setObjectsSelected(e,t){return this.withObjects(e,(e=>{const i=e.selected!==t;return e.selected=t,i}))}setObjectsHighlighted(e,t){return this.withObjects(e,(e=>{const i=e.highlighted!==t;return e.highlighted=t,i}))}setObjectsXRayed(e,t){return this.withObjects(e,(e=>{const i=e.xrayed!==t;return e.xrayed=t,i}))}setObjectsEdges(e,t){return this.withObjects(e,(e=>{const i=e.edges!==t;return e.edges=t,i}))}setObjectsColorized(e,t){return this.withObjects(e,(e=>{e.colorize=t}))}setObjectsOpacity(e,t){return this.withObjects(e,(e=>{const i=e.opacity!==t;return e.opacity=t,i}))}setObjectsPickable(e,t){return this.withObjects(e,(e=>{const i=e.pickable!==t;return e.pickable=t,i}))}setObjectsOffset(e,t){this.withObjects(e,(e=>{e.offset=t}))}withObjects(e,t){f.isString(e)&&(e=[e]);let i=!1;for(let s=0,r=e.length;s<r;s++){const r=e[s];let o=this.objects[r];if(o)i=t(o)||i;else{const e=this.modelIds;for(let s=0,a=e.length;s<a;s++){const a=e[s],n=u.globalizeObjectId(a,r);o=this.objects[n],o&&(i=t(o)||i)}}}return i}destroy(){super.destroy();for(const e in this.components)this.components.hasOwnProperty(e)&&this.components[e].destroy();this.canvas.gl=null,this.components=null,this.models=null,this.objects=null,this.visibleObjects=null,this.xrayedObjects=null,this.highlightedObjects=null,this.selectedObjects=null,this.colorizedObjects=null,this.opacityObjects=null,this.sectionPlanes=null,this.lights=null,this.lightMaps=null,this.reflectionMaps=null,this._objectIds=null,this._visibleObjectIds=null,this._xrayedObjectIds=null,this._highlightedObjectIds=null,this._selectedObjectIds=null,this._colorizedObjectIds=null,this.types=null,this.components=null,this.canvas=null,this._renderer=null,this.input=null,this._viewport=null,this._camera=null}}const _t=function(e){"LambertMaterial"===e._material._state.type?(this.vertex=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene._lightsState,r=e._geometry._state,o=e._state.billboard,a=e._state.stationary,n=i.sectionPlanes.length>0,l=!!r.compressGeometry,h=[];if(h.push("// Lambertian drawing vertex shader"),t.logarithmicDepthBufferEnabled&&h.push("#extension GL_EXT_frag_depth : enable"),h.push("attribute vec3 position;"),h.push("uniform mat4 modelMatrix;"),h.push("uniform mat4 viewMatrix;"),h.push("uniform mat4 projMatrix;"),h.push("uniform vec4 colorize;"),h.push("uniform vec3 offset;"),l&&h.push("uniform mat4 positionsDecodeMatrix;"),t.logarithmicDepthBufferEnabled&&(h.push("uniform float logDepthBufFC;"),h.push("varying float vFragDepth;")),n&&h.push("varying vec4 vWorldPosition;"),h.push("uniform vec4 lightAmbient;"),h.push("uniform vec4 materialColor;"),h.push("uniform vec3 materialEmissive;"),r.normalsBuf){h.push("attribute vec3 normal;"),h.push("uniform mat4 modelNormalMatrix;"),h.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(h.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&h.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&h.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(h.push("uniform vec3 lightPos"+e+";"),h.push("uniform vec3 lightDir"+e+";")))}l&&(h.push("vec3 octDecode(vec2 oct) {"),h.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),h.push("    if (v.z < 0.0) {"),h.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),h.push("    }"),h.push("    return normalize(v);"),h.push("}"))}if(h.push("varying vec4 vColor;"),"points"===r.primitiveName&&h.push("uniform float pointSize;"),"spherical"!==o&&"cylindrical"!==o||(h.push("void billboard(inout mat4 mat) {"),h.push("   mat[0][0] = 1.0;"),h.push("   mat[0][1] = 0.0;"),h.push("   mat[0][2] = 0.0;"),"spherical"===o&&(h.push("   mat[1][0] = 0.0;"),h.push("   mat[1][1] = 1.0;"),h.push("   mat[1][2] = 0.0;")),h.push("   mat[2][0] = 0.0;"),h.push("   mat[2][1] = 0.0;"),h.push("   mat[2][2] =1.0;"),h.push("}")),h.push("void main(void) {"),h.push("vec4 localPosition = vec4(position, 1.0); "),h.push("vec4 worldPosition;"),l&&h.push("localPosition = positionsDecodeMatrix * localPosition;"),r.normalsBuf&&(l?h.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):h.push("vec4 localNormal = vec4(normal, 0.0); "),h.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),h.push("mat4 viewNormalMatrix2 = viewNormalMatrix;")),h.push("mat4 viewMatrix2 = viewMatrix;"),h.push("mat4 modelMatrix2 = modelMatrix;"),a&&h.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===o||"cylindrical"===o?(h.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),h.push("billboard(modelMatrix2);"),h.push("billboard(viewMatrix2);"),h.push("billboard(modelViewMatrix);"),r.normalsBuf&&(h.push("mat4 modelViewNormalMatrix =  viewNormalMatrix2 * modelNormalMatrix2;"),h.push("billboard(modelNormalMatrix2);"),h.push("billboard(viewNormalMatrix2);"),h.push("billboard(modelViewNormalMatrix);")),h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(h.push("worldPosition = modelMatrix2 * localPosition;"),h.push("worldPosition.xyz = worldPosition.xyz + offset;"),h.push("vec4 viewPosition  = viewMatrix2 * worldPosition; ")),r.normalsBuf&&h.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);"),h.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),h.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),h.push("float lambertian = 1.0;"),r.normalsBuf)for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?h.push("viewLightDir = normalize(lightDir"+e+");"):h.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?h.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):h.push("viewLightDir = -normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?h.push("viewLightDir = normalize(lightDir"+e+");"):h.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);")}h.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),h.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return h.push("vColor = vec4((lightAmbient.rgb * lightAmbient.a * materialColor.rgb) + materialEmissive.rgb + (reflectedColor * materialColor.rgb), materialColor.a) * colorize;"),n&&h.push("vWorldPosition = worldPosition;"),"points"===r.primitiveName&&h.push("gl_PointSize = pointSize;"),h.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&h.push("vFragDepth = 1.0 + clipPos.w;"),h.push("gl_Position = clipPos;"),h.push("}"),h}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState;e._material._state;const s=e._geometry._state,r=i.sectionPlanes.length>0,o=t.gammaOutput,a=[];if(a.push("// Lambertian drawing fragment shader"),t.logarithmicDepthBufferEnabled&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),t.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),a.push("varying float vFragDepth;")),r){a.push("varying vec4 vWorldPosition;"),a.push("uniform bool clippable;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("varying vec4 vColor;"),o&&(a.push("uniform float gammaFactor;"),a.push("    vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push("    return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),a.push("void main(void) {"),r){a.push("if (clippable) {"),a.push("  float dist = 0.0;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");a.push("  if (dist > 0.0) { discard; }"),a.push("}")}return"points"===s.primitiveName&&(a.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),a.push("float r = dot(cxy, cxy);"),a.push("if (r > 1.0) {"),a.push("   discard;"),a.push("}")),t.logarithmicDepthBufferEnabled&&a.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o?a.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):a.push("gl_FragColor = vColor;"),a.push("}"),a}(e)):(this.vertex=function(e){const t=e.scene,i=e._material,s=e._state,r=t._sectionPlanesState,o=e._geometry._state,a=t._lightsState;let n;const l=s.billboard,h=s.stationary,c=function(e){if(!e._geometry._state.uvBuf)return!1;const t=e._material;return!!(t._ambientMap||t._occlusionMap||t._baseColorMap||t._diffuseMap||t._alphaMap||t._specularMap||t._glossinessMap||t._specularGlossinessMap||t._emissiveMap||t._metallicMap||t._roughnessMap||t._metallicRoughnessMap||t._reflectivityMap||t._normalMap)}(e),u=mt(e),d=r.sectionPlanes.length>0,p=gt(e),_=!!o.compressGeometry,f=[];if(f.push("// Drawing vertex shader"),u&&i._normalMap&&f.push("#extension GL_OES_standard_derivatives : enable"),t.logarithmicDepthBufferEnabled&&f.push("#extension GL_EXT_frag_depth : enable"),f.push("attribute  vec3 position;"),_&&f.push("uniform mat4 positionsDecodeMatrix;"),f.push("uniform  mat4 modelMatrix;"),f.push("uniform  mat4 viewMatrix;"),f.push("uniform  mat4 projMatrix;"),f.push("varying  vec3 vViewPosition;"),f.push("uniform  vec3 offset;"),d&&f.push("varying vec4 vWorldPosition;"),t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("varying float vFragDepth;")),a.lightMaps.length>0&&f.push("varying    vec3 vWorldNormal;"),u){f.push("attribute  vec3 normal;"),f.push("uniform    mat4 modelNormalMatrix;"),f.push("uniform    mat4 viewNormalMatrix;"),f.push("varying    vec3 vViewNormal;");for(let e=0,t=a.lights.length;e<t;e++)n=a.lights[e],"ambient"!==n.type&&("dir"===n.type&&f.push("uniform vec3 lightDir"+e+";"),"point"===n.type&&f.push("uniform vec3 lightPos"+e+";"),"spot"===n.type&&(f.push("uniform vec3 lightPos"+e+";"),f.push("uniform vec3 lightDir"+e+";")),"dir"===n.type&&"view"===n.space||f.push("varying vec4 vViewLightReverseDirAndDist"+e+";"));_&&(f.push("vec3 octDecode(vec2 oct) {"),f.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),f.push("    if (v.z < 0.0) {"),f.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),f.push("    }"),f.push("    return normalize(v);"),f.push("}"))}if(c&&(f.push("attribute vec2 uv;"),f.push("varying vec2 vUV;"),_&&f.push("uniform mat3 uvDecodeMatrix;")),o.colors&&(f.push("attribute vec4 color;"),f.push("varying vec4 vColor;")),"points"===o.primitiveName&&f.push("uniform float pointSize;"),"spherical"!==l&&"cylindrical"!==l||(f.push("void billboard(inout mat4 mat) {"),f.push("   mat[0][0] = 1.0;"),f.push("   mat[0][1] = 0.0;"),f.push("   mat[0][2] = 0.0;"),"spherical"===l&&(f.push("   mat[1][0] = 0.0;"),f.push("   mat[1][1] = 1.0;"),f.push("   mat[1][2] = 0.0;")),f.push("   mat[2][0] = 0.0;"),f.push("   mat[2][1] = 0.0;"),f.push("   mat[2][2] =1.0;"),f.push("}")),p){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&(f.push("uniform mat4 shadowViewMatrix"+e+";"),f.push("uniform mat4 shadowProjMatrix"+e+";"),f.push("varying vec4 vShadowPosFromLight"+e+";"))}if(f.push("void main(void) {"),f.push("vec4 localPosition = vec4(position, 1.0); "),f.push("vec4 worldPosition;"),_&&f.push("localPosition = positionsDecodeMatrix * localPosition;"),u&&(_?f.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):f.push("vec4 localNormal = vec4(normal, 0.0); "),f.push("mat4 modelNormalMatrix2    = modelNormalMatrix;"),f.push("mat4 viewNormalMatrix2     = viewNormalMatrix;")),f.push("mat4 viewMatrix2           = viewMatrix;"),f.push("mat4 modelMatrix2          = modelMatrix;"),h&&f.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===l||"cylindrical"===l?(f.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),f.push("billboard(modelMatrix2);"),f.push("billboard(viewMatrix2);"),f.push("billboard(modelViewMatrix);"),u&&(f.push("mat4 modelViewNormalMatrix =  viewNormalMatrix2 * modelNormalMatrix2;"),f.push("billboard(modelNormalMatrix2);"),f.push("billboard(viewNormalMatrix2);"),f.push("billboard(modelViewNormalMatrix);")),f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(f.push("worldPosition = modelMatrix2 * localPosition;"),f.push("worldPosition.xyz = worldPosition.xyz + offset;"),f.push("vec4 viewPosition  = viewMatrix2 * worldPosition; ")),u){f.push("vec3 worldNormal = (modelNormalMatrix2 * localNormal).xyz; "),a.lightMaps.length>0&&f.push("vWorldNormal = worldNormal;"),f.push("vViewNormal = normalize((viewNormalMatrix2 * vec4(worldNormal, 1.0)).xyz);"),f.push("vec3 tmpVec3;"),f.push("float lightDist;");for(let e=0,t=a.lights.length;e<t;e++)n=a.lights[e],"ambient"!==n.type&&("dir"===n.type&&"world"===n.space&&(f.push("tmpVec3 = vec3(viewMatrix2 * vec4(lightDir"+e+", 0.0) ).xyz;"),f.push("vViewLightReverseDirAndDist"+e+" = vec4(-tmpVec3, 0.0);")),"point"===n.type&&("world"===n.space?(f.push("tmpVec3 = (viewMatrix2 * vec4(lightPos"+e+", 1.0)).xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")):(f.push("tmpVec3 = lightPos"+e+".xyz - viewPosition.xyz;"),f.push("lightDist = abs(length(tmpVec3));")),f.push("vViewLightReverseDirAndDist"+e+" = vec4(tmpVec3, lightDist);")))}if(c&&(_?f.push("vUV = (uvDecodeMatrix * vec3(uv, 1.0)).xy;"):f.push("vUV = uv;")),o.colors&&f.push("vColor = color;"),"points"===o.primitiveName&&f.push("gl_PointSize = pointSize;"),d&&f.push("vWorldPosition = worldPosition;"),f.push("   vViewPosition = viewPosition.xyz;"),f.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&f.push("vFragDepth = 1.0 + clipPos.w;"),f.push("gl_Position = clipPos;"),p){f.push("const mat4 texUnitConverter = mat4(0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0);"),f.push("vec4 tempx; ");for(let e=0,t=a.lights.length;e<t;e++)a.lights[e].castsShadow&&f.push("vShadowPosFromLight"+e+" = texUnitConverter * shadowProjMatrix"+e+" * (shadowViewMatrix"+e+" * worldPosition); ")}return f.push("}"),f}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=e._material,s=e._geometry._state,r=e.scene._sectionPlanesState,o=e.scene._lightsState,a=e._material._state,n=r.sectionPlanes.length>0,l=mt(e),h=s.uvBuf,c="PhongMaterial"===a.type,u="MetallicMaterial"===a.type,d="SpecularMaterial"===a.type,p=gt(e);t.gammaInput;const _=t.gammaOutput,f=[];if(f.push("// Drawing fragment shader"),t.logarithmicDepthBufferEnabled&&f.push("#extension GL_EXT_frag_depth : enable"),l&&i._normalMap&&f.push("#extension GL_OES_standard_derivatives : enable"),f.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),f.push("precision highp float;"),f.push("precision highp int;"),f.push("#else"),f.push("precision mediump float;"),f.push("precision mediump int;"),f.push("#endif"),t.logarithmicDepthBufferEnabled&&(f.push("uniform float logDepthBufFC;"),f.push("varying float vFragDepth;")),p&&(f.push("float unpackDepth (vec4 color) {"),f.push("  const vec4 bitShift = vec4(1.0, 1.0/256.0, 1.0/(256.0 * 256.0), 1.0/(256.0*256.0*256.0));"),f.push("  return dot(color, bitShift);"),f.push("}")),f.push("uniform float gammaFactor;"),f.push("vec4 linearToLinear( in vec4 value ) {"),f.push("  return value;"),f.push("}"),f.push("vec4 sRGBToLinear( in vec4 value ) {"),f.push("  return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),f.push("}"),f.push("vec4 gammaToLinear( in vec4 value) {"),f.push("  return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),f.push("}"),_&&(f.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),f.push("  return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),f.push("}")),n){f.push("varying vec4 vWorldPosition;"),f.push("uniform bool clippable;");for(var g=0;g<r.sectionPlanes.length;g++)f.push("uniform bool sectionPlaneActive"+g+";"),f.push("uniform vec3 sectionPlanePos"+g+";"),f.push("uniform vec3 sectionPlaneDir"+g+";")}if(l&&(o.lightMaps.length>0&&(f.push("uniform samplerCube lightMap;"),f.push("uniform mat4 viewNormalMatrix;")),o.reflectionMaps.length>0&&f.push("uniform samplerCube reflectionMap;"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("uniform mat4 viewMatrix;"),f.push("#define PI 3.14159265359"),f.push("#define RECIPROCAL_PI 0.31830988618"),f.push("#define RECIPROCAL_PI2 0.15915494"),f.push("#define EPSILON 1e-6"),f.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),f.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),f.push("   return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),f.push("}"),f.push("struct IncidentLight {"),f.push("   vec3 color;"),f.push("   vec3 direction;"),f.push("};"),f.push("struct ReflectedLight {"),f.push("   vec3 diffuse;"),f.push("   vec3 specular;"),f.push("};"),f.push("struct Geometry {"),f.push("   vec3 position;"),f.push("   vec3 viewNormal;"),f.push("   vec3 worldNormal;"),f.push("   vec3 viewEyeDir;"),f.push("};"),f.push("struct Material {"),f.push("   vec3    diffuseColor;"),f.push("   float   specularRoughness;"),f.push("   vec3    specularColor;"),f.push("   float   shine;"),f.push("};"),c&&((o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePhongLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push("   vec3 irradiance = "+ft[o.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),f.push("   irradiance *= PI;"),f.push("   vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push("   reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push("   vec3 reflectVec             = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push("   vec3 radiance               = textureCube(reflectionMap, reflectVec).rgb * 0.2;"),f.push("   radiance *= PI;"),f.push("   reflectedLight.specular     += radiance;")),f.push("}")),f.push("void computePhongLighting(const in IncidentLight directLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push("   float dotNL     = saturate(dot(geometry.viewNormal, directLight.direction));"),f.push("   vec3 irradiance = dotNL * directLight.color * PI;"),f.push("   reflectedLight.diffuse  += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push("   reflectedLight.specular += directLight.color * material.specularColor * pow(max(dot(reflect(-directLight.direction, -geometry.viewNormal), geometry.viewEyeDir), 0.0), material.shine);"),f.push("}")),(u||d)&&(f.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),f.push("   float r = ggxRoughness + 0.0001;"),f.push("   return (2.0 / (r * r) - 2.0);"),f.push("}"),f.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push("   float maxMIPLevelScalar = float( maxMIPLevel );"),f.push("   float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),f.push("   return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),f.push("}"),o.reflectionMaps.length>0&&(f.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),f.push("   float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),f.push("   vec3 envMapColor = "+ft[o.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),f.push("  return envMapColor;"),f.push("}")),f.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),f.push("   float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),f.push("   return ( 1.0 - specularColor ) * fresnel + specularColor;"),f.push("}"),f.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push("   float a2 = ( alpha * alpha );"),f.push("   float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push("   float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push("   return 1.0 / ( gl * gv );"),f.push("}"),f.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),f.push("   float a2 = ( alpha * alpha );"),f.push("   float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),f.push("   float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),f.push("   return 0.5 / max( gv + gl, EPSILON );"),f.push("}"),f.push("float D_GGX(const in float alpha, const in float dotNH) {"),f.push("   float a2 = ( alpha * alpha );"),f.push("   float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),f.push("   return RECIPROCAL_PI * a2 / ( denom * denom);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push("   float alpha = ( roughness * roughness );"),f.push("   vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),f.push("   float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),f.push("   float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),f.push("   float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),f.push("   float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),f.push("   vec3  F = F_Schlick( specularColor, dotLH );"),f.push("   float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),f.push("   float D = D_GGX( alpha, dotNH );"),f.push("   return F * (G * D);"),f.push("}"),f.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),f.push("   float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),f.push("   const vec4 c0 = vec4( -1, -0.0275, -0.572,  0.022);"),f.push("   const vec4 c1 = vec4(  1,  0.0425,   1.04, -0.04);"),f.push("   vec4 r = roughness * c0 + c1;"),f.push("   float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),f.push("   vec2 AB    = vec2(-1.04, 1.04) * a004 + r.zw;"),f.push("   return specularColor * AB.x + AB.y;"),f.push("}"),(o.lightMaps.length>0||o.reflectionMaps.length>0)&&(f.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),o.lightMaps.length>0&&(f.push("   vec3 irradiance = sRGBToLinear(textureCube(lightMap, geometry.worldNormal)).rgb;"),f.push("   irradiance *= PI;"),f.push("   vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),f.push("   reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),o.reflectionMaps.length>0&&(f.push("   vec3 reflectVec             = reflect(-geometry.viewEyeDir, geometry.viewNormal);"),f.push("   reflectVec                  = inverseTransformDirection(reflectVec, viewMatrix);"),f.push("   float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),f.push("   vec3 radiance               = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),f.push("   vec3 specularBRDFContrib    = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),f.push("   reflectedLight.specular     += radiance * specularBRDFContrib;")),f.push("}")),f.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),f.push("   float dotNL     = saturate(dot(geometry.viewNormal, incidentLight.direction));"),f.push("   vec3 irradiance = dotNL * incidentLight.color * PI;"),f.push("   reflectedLight.diffuse  += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),f.push("   reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),f.push("}"))),f.push("varying vec3 vViewPosition;"),s.colors&&f.push("varying vec4 vColor;"),h&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._occlusionMap||i._alphaMap)&&f.push("varying vec2 vUV;"),l&&(o.lightMaps.length>0&&f.push("varying vec3 vWorldNormal;"),f.push("varying vec3 vViewNormal;")),a.ambient&&f.push("uniform vec3 materialAmbient;"),a.baseColor&&f.push("uniform vec3 materialBaseColor;"),void 0!==a.alpha&&null!==a.alpha&&f.push("uniform vec4 materialAlphaModeCutoff;"),a.emissive&&f.push("uniform vec3 materialEmissive;"),a.diffuse&&f.push("uniform vec3 materialDiffuse;"),void 0!==a.glossiness&&null!==a.glossiness&&f.push("uniform float materialGlossiness;"),void 0!==a.shininess&&null!==a.shininess&&f.push("uniform float materialShininess;"),a.specular&&f.push("uniform vec3 materialSpecular;"),void 0!==a.metallic&&null!==a.metallic&&f.push("uniform float materialMetallic;"),void 0!==a.roughness&&null!==a.roughness&&f.push("uniform float materialRoughness;"),void 0!==a.specularF0&&null!==a.specularF0&&f.push("uniform float materialSpecularF0;"),h&&i._ambientMap&&(f.push("uniform sampler2D ambientMap;"),i._ambientMap._state.matrix&&f.push("uniform mat4 ambientMapMatrix;")),h&&i._baseColorMap&&(f.push("uniform sampler2D baseColorMap;"),i._baseColorMap._state.matrix&&f.push("uniform mat4 baseColorMapMatrix;")),h&&i._diffuseMap&&(f.push("uniform sampler2D diffuseMap;"),i._diffuseMap._state.matrix&&f.push("uniform mat4 diffuseMapMatrix;")),h&&i._emissiveMap&&(f.push("uniform sampler2D emissiveMap;"),i._emissiveMap._state.matrix&&f.push("uniform mat4 emissiveMapMatrix;")),l&&h&&i._metallicMap&&(f.push("uniform sampler2D metallicMap;"),i._metallicMap._state.matrix&&f.push("uniform mat4 metallicMapMatrix;")),l&&h&&i._roughnessMap&&(f.push("uniform sampler2D roughnessMap;"),i._roughnessMap._state.matrix&&f.push("uniform mat4 roughnessMapMatrix;")),l&&h&&i._metallicRoughnessMap&&(f.push("uniform sampler2D metallicRoughnessMap;"),i._metallicRoughnessMap._state.matrix&&f.push("uniform mat4 metallicRoughnessMapMatrix;")),l&&i._normalMap&&(f.push("uniform sampler2D normalMap;"),i._normalMap._state.matrix&&f.push("uniform mat4 normalMapMatrix;"),f.push("vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm, vec2 uv ) {"),f.push("      vec3 q0 = vec3( dFdx( eye_pos.x ), dFdx( eye_pos.y ), dFdx( eye_pos.z ) );"),f.push("      vec3 q1 = vec3( dFdy( eye_pos.x ), dFdy( eye_pos.y ), dFdy( eye_pos.z ) );"),f.push("      vec2 st0 = dFdx( uv.st );"),f.push("      vec2 st1 = dFdy( uv.st );"),f.push("      vec3 S = normalize( q0 * st1.t - q1 * st0.t );"),f.push("      vec3 T = normalize( -q0 * st1.s + q1 * st0.s );"),f.push("      vec3 N = normalize( surf_norm );"),f.push("      vec3 mapN = texture2D( normalMap, uv ).xyz * 2.0 - 1.0;"),f.push("      mat3 tsn = mat3( S, T, N );"),f.push("      return normalize( tsn * mapN );"),f.push("}")),h&&i._occlusionMap&&(f.push("uniform sampler2D occlusionMap;"),i._occlusionMap._state.matrix&&f.push("uniform mat4 occlusionMapMatrix;")),h&&i._alphaMap&&(f.push("uniform sampler2D alphaMap;"),i._alphaMap._state.matrix&&f.push("uniform mat4 alphaMapMatrix;")),l&&h&&i._specularMap&&(f.push("uniform sampler2D specularMap;"),i._specularMap._state.matrix&&f.push("uniform mat4 specularMapMatrix;")),l&&h&&i._glossinessMap&&(f.push("uniform sampler2D glossinessMap;"),i._glossinessMap._state.matrix&&f.push("uniform mat4 glossinessMapMatrix;")),l&&h&&i._specularGlossinessMap&&(f.push("uniform sampler2D materialSpecularGlossinessMap;"),i._specularGlossinessMap._state.matrix&&f.push("uniform mat4 materialSpecularGlossinessMapMatrix;")),l&&(i._diffuseFresnel||i._specularFresnel||i._alphaFresnel||i._emissiveFresnel||i._reflectivityFresnel)&&(f.push("float fresnel(vec3 eyeDir, vec3 normal, float edgeBias, float centerBias, float power) {"),f.push("    float fr = abs(dot(eyeDir, normal));"),f.push("    float finalFr = clamp((fr - edgeBias) / (centerBias - edgeBias), 0.0, 1.0);"),f.push("    return pow(finalFr, power);"),f.push("}"),i._diffuseFresnel&&(f.push("uniform float  diffuseFresnelCenterBias;"),f.push("uniform float  diffuseFresnelEdgeBias;"),f.push("uniform float  diffuseFresnelPower;"),f.push("uniform vec3   diffuseFresnelCenterColor;"),f.push("uniform vec3   diffuseFresnelEdgeColor;")),i._specularFresnel&&(f.push("uniform float  specularFresnelCenterBias;"),f.push("uniform float  specularFresnelEdgeBias;"),f.push("uniform float  specularFresnelPower;"),f.push("uniform vec3   specularFresnelCenterColor;"),f.push("uniform vec3   specularFresnelEdgeColor;")),i._alphaFresnel&&(f.push("uniform float  alphaFresnelCenterBias;"),f.push("uniform float  alphaFresnelEdgeBias;"),f.push("uniform float  alphaFresnelPower;"),f.push("uniform vec3   alphaFresnelCenterColor;"),f.push("uniform vec3   alphaFresnelEdgeColor;")),i._reflectivityFresnel&&(f.push("uniform float  materialSpecularF0FresnelCenterBias;"),f.push("uniform float  materialSpecularF0FresnelEdgeBias;"),f.push("uniform float  materialSpecularF0FresnelPower;"),f.push("uniform vec3   materialSpecularF0FresnelCenterColor;"),f.push("uniform vec3   materialSpecularF0FresnelEdgeColor;")),i._emissiveFresnel&&(f.push("uniform float  emissiveFresnelCenterBias;"),f.push("uniform float  emissiveFresnelEdgeBias;"),f.push("uniform float  emissiveFresnelPower;"),f.push("uniform vec3   emissiveFresnelCenterColor;"),f.push("uniform vec3   emissiveFresnelEdgeColor;"))),f.push("uniform vec4   lightAmbient;"),l)for(let e=0,t=o.lights.length;e<t;e++){const t=o.lights[e];"ambient"!==t.type&&(f.push("uniform vec4 lightColor"+e+";"),"point"===t.type&&f.push("uniform vec3 lightAttenuation"+e+";"),"dir"===t.type&&"view"===t.space&&f.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&"view"===t.space?f.push("uniform vec3 lightPos"+e+";"):f.push("varying vec4 vViewLightReverseDirAndDist"+e+";"))}if(p)for(let e=0,t=o.lights.length;e<t;e++)o.lights[e].castsShadow&&(f.push("varying vec4 vShadowPosFromLight"+e+";"),f.push("uniform sampler2D shadowMap"+e+";"));if(f.push("uniform vec4 colorize;"),f.push("void main(void) {"),n){for(f.push("if (clippable) {"),f.push("  float dist = 0.0;"),g=0;g<r.sectionPlanes.length;g++)f.push("if (sectionPlaneActive"+g+") {"),f.push("   dist += clamp(dot(-sectionPlaneDir"+g+".xyz, vWorldPosition.xyz - sectionPlanePos"+g+".xyz), 0.0, 1000.0);"),f.push("}");f.push("  if (dist > 0.0) { discard; }"),f.push("}")}if("points"===s.primitiveName&&(f.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),f.push("float r = dot(cxy, cxy);"),f.push("if (r > 1.0) {"),f.push("   discard;"),f.push("}")),f.push("float occlusion = 1.0;"),a.ambient?f.push("vec3 ambientColor = materialAmbient;"):f.push("vec3 ambientColor = vec3(1.0, 1.0, 1.0);"),a.diffuse?f.push("vec3 diffuseColor = materialDiffuse;"):a.baseColor?f.push("vec3 diffuseColor = materialBaseColor;"):f.push("vec3 diffuseColor = vec3(1.0, 1.0, 1.0);"),s.colors&&f.push("diffuseColor *= vColor.rgb;"),a.emissive?f.push("vec3 emissiveColor = materialEmissive;"):f.push("vec3  emissiveColor = vec3(0.0, 0.0, 0.0);"),a.specular?f.push("vec3 specular = materialSpecular;"):f.push("vec3 specular = vec3(1.0, 1.0, 1.0);"),void 0!==a.alpha?f.push("float alpha = materialAlphaModeCutoff[0];"):f.push("float alpha = 1.0;"),s.colors&&f.push("alpha *= vColor.a;"),void 0!==a.glossiness?f.push("float glossiness = materialGlossiness;"):f.push("float glossiness = 1.0;"),void 0!==a.metallic?f.push("float metallic = materialMetallic;"):f.push("float metallic = 1.0;"),void 0!==a.roughness?f.push("float roughness = materialRoughness;"):f.push("float roughness = 1.0;"),void 0!==a.specularF0?f.push("float specularF0 = materialSpecularF0;"):f.push("float specularF0 = 1.0;"),h&&(l&&i._normalMap||i._ambientMap||i._baseColorMap||i._diffuseMap||i._occlusionMap||i._emissiveMap||i._metallicMap||i._roughnessMap||i._metallicRoughnessMap||i._specularMap||i._glossinessMap||i._specularGlossinessMap||i._alphaMap)&&(f.push("vec4 texturePos = vec4(vUV.s, vUV.t, 1.0, 1.0);"),f.push("vec2 textureCoord;")),h&&i._ambientMap&&(i._ambientMap._state.matrix?f.push("textureCoord = (ambientMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 ambientTexel = texture2D(ambientMap, textureCoord).rgb;"),f.push("ambientTexel = "+ft[i._ambientMap._state.encoding]+"(ambientTexel);"),f.push("ambientColor *= ambientTexel.rgb;")),h&&i._diffuseMap&&(i._diffuseMap._state.matrix?f.push("textureCoord = (diffuseMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 diffuseTexel = texture2D(diffuseMap, textureCoord);"),f.push("diffuseTexel = "+ft[i._diffuseMap._state.encoding]+"(diffuseTexel);"),f.push("diffuseColor *= diffuseTexel.rgb;"),f.push("alpha *= diffuseTexel.a;")),h&&i._baseColorMap&&(i._baseColorMap._state.matrix?f.push("textureCoord = (baseColorMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 baseColorTexel = texture2D(baseColorMap, textureCoord);"),f.push("baseColorTexel = "+ft[i._baseColorMap._state.encoding]+"(baseColorTexel);"),f.push("diffuseColor *= baseColorTexel.rgb;"),f.push("alpha *= baseColorTexel.a;")),h&&i._emissiveMap&&(i._emissiveMap._state.matrix?f.push("textureCoord = (emissiveMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 emissiveTexel = texture2D(emissiveMap, textureCoord);"),f.push("emissiveTexel = "+ft[i._emissiveMap._state.encoding]+"(emissiveTexel);"),f.push("emissiveColor = emissiveTexel.rgb;")),h&&i._alphaMap&&(i._alphaMap._state.matrix?f.push("textureCoord = (alphaMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("alpha *= texture2D(alphaMap, textureCoord).r;")),h&&i._occlusionMap&&(i._occlusionMap._state.matrix?f.push("textureCoord = (occlusionMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("occlusion *= texture2D(occlusionMap, textureCoord).r;")),l&&(o.lights.length>0||o.lightMaps.length>0||o.reflectionMaps.length>0)){h&&i._normalMap?(i._normalMap._state.matrix?f.push("textureCoord = (normalMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 viewNormal = perturbNormal2Arb( vViewPosition, normalize(vViewNormal), textureCoord );")):f.push("vec3 viewNormal = normalize(vViewNormal);"),h&&i._specularMap&&(i._specularMap._state.matrix?f.push("textureCoord = (specularMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("specular *= texture2D(specularMap, textureCoord).rgb;")),h&&i._glossinessMap&&(i._glossinessMap._state.matrix?f.push("textureCoord = (glossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("glossiness *= texture2D(glossinessMap, textureCoord).r;")),h&&i._specularGlossinessMap&&(i._specularGlossinessMap._state.matrix?f.push("textureCoord = (materialSpecularGlossinessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec4 specGlossRGB = texture2D(materialSpecularGlossinessMap, textureCoord).rgba;"),f.push("specular *= specGlossRGB.rgb;"),f.push("glossiness *= specGlossRGB.a;")),h&&i._metallicMap&&(i._metallicMap._state.matrix?f.push("textureCoord = (metallicMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("metallic *= texture2D(metallicMap, textureCoord).r;")),h&&i._roughnessMap&&(i._roughnessMap._state.matrix?f.push("textureCoord = (roughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("roughness *= texture2D(roughnessMap, textureCoord).r;")),h&&i._metallicRoughnessMap&&(i._metallicRoughnessMap._state.matrix?f.push("textureCoord = (metallicRoughnessMapMatrix * texturePos).xy;"):f.push("textureCoord = texturePos.xy;"),f.push("vec3 metalRoughRGB = texture2D(metallicRoughnessMap, textureCoord).rgb;"),f.push("metallic *= metalRoughRGB.b;"),f.push("roughness *= metalRoughRGB.g;")),f.push("vec3 viewEyeDir = normalize(-vViewPosition);"),i._diffuseFresnel&&(f.push("float diffuseFresnel = fresnel(viewEyeDir, viewNormal, diffuseFresnelEdgeBias, diffuseFresnelCenterBias, diffuseFresnelPower);"),f.push("diffuseColor *= mix(diffuseFresnelEdgeColor, diffuseFresnelCenterColor, diffuseFresnel);")),i._specularFresnel&&(f.push("float specularFresnel = fresnel(viewEyeDir, viewNormal, specularFresnelEdgeBias, specularFresnelCenterBias, specularFresnelPower);"),f.push("specular *= mix(specularFresnelEdgeColor, specularFresnelCenterColor, specularFresnel);")),i._alphaFresnel&&(f.push("float alphaFresnel = fresnel(viewEyeDir, viewNormal, alphaFresnelEdgeBias, alphaFresnelCenterBias, alphaFresnelPower);"),f.push("alpha *= mix(alphaFresnelEdgeColor.r, alphaFresnelCenterColor.r, alphaFresnel);")),i._emissiveFresnel&&(f.push("float emissiveFresnel = fresnel(viewEyeDir, viewNormal, emissiveFresnelEdgeBias, emissiveFresnelCenterBias, emissiveFresnelPower);"),f.push("emissiveColor *= mix(emissiveFresnelEdgeColor, emissiveFresnelCenterColor, emissiveFresnel);")),f.push("if (materialAlphaModeCutoff[1] == 1.0 && alpha < materialAlphaModeCutoff[2]) {"),f.push("   discard;"),f.push("}"),f.push("IncidentLight  light;"),f.push("Material       material;"),f.push("Geometry       geometry;"),f.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),f.push("vec3           viewLightDir;"),c&&(f.push("material.diffuseColor      = diffuseColor;"),f.push("material.specularColor     = specular;"),f.push("material.shine             = materialShininess;")),d&&(f.push("float oneMinusSpecularStrength = 1.0 - max(max(specular.r, specular.g ),specular.b);"),f.push("material.diffuseColor      = diffuseColor * oneMinusSpecularStrength;"),f.push("material.specularRoughness = clamp( 1.0 - glossiness, 0.04, 1.0 );"),f.push("material.specularColor     = specular;")),u&&(f.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),f.push("material.diffuseColor      = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),f.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),f.push("material.specularColor     = mix(vec3(dielectricSpecular), diffuseColor, metallic);")),f.push("geometry.position      = vViewPosition;"),o.lightMaps.length>0&&f.push("geometry.worldNormal   = normalize(vWorldNormal);"),f.push("geometry.viewNormal    = viewNormal;"),f.push("geometry.viewEyeDir    = viewEyeDir;"),c&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePhongLightMapping(geometry, material, reflectedLight);"),(d||u)&&(o.lightMaps.length>0||o.reflectionMaps.length>0)&&f.push("computePBRLightMapping(geometry, material, reflectedLight);"),f.push("float shadow = 1.0;"),f.push("float shadowAcneRemover = 0.007;"),f.push("vec3 fragmentDepth;"),f.push("float texelSize = 1.0 / 1024.0;"),f.push("float amountInLight = 0.0;"),f.push("vec3 shadowCoord;"),f.push("vec4 rgbaDepth;"),f.push("float depth;");for(let e=0,t=o.lights.length;e<t;e++){const t=o.lights[e];"ambient"!==t.type&&("dir"===t.type&&"view"===t.space?f.push("viewLightDir = -normalize(lightDir"+e+");"):"point"===t.type&&"view"===t.space?f.push("viewLightDir = normalize(lightPos"+e+" - vViewPosition);"):f.push("viewLightDir = normalize(vViewLightReverseDirAndDist"+e+".xyz);"),p&&t.castsShadow?(f.push("shadow = 0.0;"),f.push("fragmentDepth = vShadowPosFromLight"+e+".xyz;"),f.push("fragmentDepth.z -= shadowAcneRemover;"),f.push("for (int x = -3; x <= 3; x++) {"),f.push("  for (int y = -3; y <= 3; y++) {"),f.push("      float texelDepth = unpackDepth(texture2D(shadowMap"+e+", fragmentDepth.xy + vec2(x, y) * texelSize));"),f.push("      if (fragmentDepth.z < texelDepth) {"),f.push("          shadow += 1.0;"),f.push("      }"),f.push("  }"),f.push("}"),f.push("shadow = shadow / 9.0;"),f.push("light.color =  lightColor"+e+".rgb * (lightColor"+e+".a * shadow);")):f.push("light.color =  lightColor"+e+".rgb * (lightColor"+e+".a );"),f.push("light.direction = viewLightDir;"),c&&f.push("computePhongLighting(light, geometry, material, reflectedLight);"),(d||u)&&f.push("computePBRLighting(light, geometry, material, reflectedLight);"))}c?f.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * diffuseColor) + ((occlusion * (( reflectedLight.diffuse + reflectedLight.specular)))) + emissiveColor;"):f.push("vec3 outgoingLight = (occlusion * (reflectedLight.diffuse)) + (occlusion * reflectedLight.specular) + emissiveColor;")}else f.push("ambientColor *= (lightAmbient.rgb * lightAmbient.a);"),f.push("vec3 outgoingLight = emissiveColor + ambientColor;");return f.push("gl_FragColor = vec4(outgoingLight, alpha) * colorize;"),_&&f.push("gl_FragColor = linearToGamma(gl_FragColor, gammaFactor);"),t.logarithmicDepthBufferEnabled&&f.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),f.push("}"),f}(e))},ft={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"};function gt(e){if(!e.receivesShadow)return!1;const t=e.scene._lightsState.lights;if(!t||0===t.length)return!1;for(let e=0,i=t.length;e<i;e++)if(t[e].castsShadow)return!0;return!1}function mt(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}const vt=u.vec3(),bt=new e({}),Pt=function(e,t){this.id=bt.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new _t(t),this._allocate(t)},yt={};Pt.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,(t.gammaInput?"gi;":";")+(t.gammaOutput?"go":""),t._lightsState.getHash(),t._sectionPlanesState.getHash(),e._geometry._state.hash,e._material._state.hash,e._state.drawHash].join(";");let s=yt[i];if(!s){if(s=new Pt(i,e),s.errors)return console.log(s.errors.join("\n")),null;yt[i]=s,d.memory.programs++}return s._useCount++,s},Pt.prototype.put=function(){0==--this._useCount&&(bt.removeItem(this.id),this._program&&this._program.destroy(),delete yt[this._hash],d.memory.programs--)},Pt.prototype.webglContextRestored=function(){this._program=null},Pt.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=V.MAX_TEXTURE_UNITS,s=t.scene,r=t._material,o=s.canvas.gl,a=this._program,n=t._state,l=t._material._state,h=t._geometry._state,c=s.camera,u=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,u?e.getRTCViewMatrix(n.rtcCenterHash,u):c.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,c.viewNormalMatrix),n.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t],s=r.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,s?1:0),s){const s=i[t];o.uniform3fv(e.pos,u?O(s.dist,s.dir,u,vt):s.pos),o.uniform3fv(e.dir,s.dir)}}}}if(l.id!==this._lastMaterialId){e.textureUnit=this._baseTextureUnit;const t=l.backfaces;e.backfaces!==t&&(t?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=t);const s=l.frontface;switch(e.frontface!==s&&(s?o.frontFace(o.CCW):o.frontFace(o.CW),e.frontface=s),e.lineWidth!==l.lineWidth&&(o.lineWidth(l.lineWidth),e.lineWidth=l.lineWidth),this._uPointSize&&o.uniform1f(this._uPointSize,l.pointSize),l.type){case"LambertMaterial":this._uMaterialAmbient&&o.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialColor&&o.uniform4f(this._uMaterialColor,l.color[0],l.color[1],l.color[2],l.alpha),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive);break;case"PhongMaterial":this._uMaterialShininess&&o.uniform1f(this._uMaterialShininess,l.shininess),this._uMaterialAmbient&&o.uniform3fv(this._uMaterialAmbient,l.ambient),this._uMaterialDiffuse&&o.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&o.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0),r._ambientMap&&r._ambientMap._state.texture&&this._uMaterialAmbientMap&&(a.bindTexture(this._uMaterialAmbientMap,r._ambientMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMaterialAmbientMapMatrix&&o.uniformMatrix4fv(this._uMaterialAmbientMapMatrix,!1,r._ambientMap._state.matrix)),r._diffuseMap&&r._diffuseMap._state.texture&&this._uDiffuseMap&&(a.bindTexture(this._uDiffuseMap,r._diffuseMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&o.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,r._diffuseMap._state.matrix)),r._specularMap&&r._specularMap._state.texture&&this._uSpecularMap&&(a.bindTexture(this._uSpecularMap,r._specularMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&o.uniformMatrix4fv(this._uSpecularMapMatrix,!1,r._specularMap._state.matrix)),r._emissiveMap&&r._emissiveMap._state.texture&&this._uEmissiveMap&&(a.bindTexture(this._uEmissiveMap,r._emissiveMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,r._emissiveMap._state.matrix)),r._alphaMap&&r._alphaMap._state.texture&&this._uAlphaMap&&(a.bindTexture(this._uAlphaMap,r._alphaMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,r._alphaMap._state.matrix)),r._reflectivityMap&&r._reflectivityMap._state.texture&&this._uReflectivityMap&&(a.bindTexture(this._uReflectivityMap,r._reflectivityMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,this._uReflectivityMapMatrix&&o.uniformMatrix4fv(this._uReflectivityMapMatrix,!1,r._reflectivityMap._state.matrix)),r._normalMap&&r._normalMap._state.texture&&this._uNormalMap&&(a.bindTexture(this._uNormalMap,r._normalMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,r._normalMap._state.matrix)),r._occlusionMap&&r._occlusionMap._state.texture&&this._uOcclusionMap&&(a.bindTexture(this._uOcclusionMap,r._occlusionMap._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,r._occlusionMap._state.matrix)),r._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias&&o.uniform1f(this._uDiffuseFresnelEdgeBias,r._diffuseFresnel.edgeBias),this._uDiffuseFresnelCenterBias&&o.uniform1f(this._uDiffuseFresnelCenterBias,r._diffuseFresnel.centerBias),this._uDiffuseFresnelEdgeColor&&o.uniform3fv(this._uDiffuseFresnelEdgeColor,r._diffuseFresnel.edgeColor),this._uDiffuseFresnelCenterColor&&o.uniform3fv(this._uDiffuseFresnelCenterColor,r._diffuseFresnel.centerColor),this._uDiffuseFresnelPower&&o.uniform1f(this._uDiffuseFresnelPower,r._diffuseFresnel.power)),r._specularFresnel&&(this._uSpecularFresnelEdgeBias&&o.uniform1f(this._uSpecularFresnelEdgeBias,r._specularFresnel.edgeBias),this._uSpecularFresnelCenterBias&&o.uniform1f(this._uSpecularFresnelCenterBias,r._specularFresnel.centerBias),this._uSpecularFresnelEdgeColor&&o.uniform3fv(this._uSpecularFresnelEdgeColor,r._specularFresnel.edgeColor),this._uSpecularFresnelCenterColor&&o.uniform3fv(this._uSpecularFresnelCenterColor,r._specularFresnel.centerColor),this._uSpecularFresnelPower&&o.uniform1f(this._uSpecularFresnelPower,r._specularFresnel.power)),r._alphaFresnel&&(this._uAlphaFresnelEdgeBias&&o.uniform1f(this._uAlphaFresnelEdgeBias,r._alphaFresnel.edgeBias),this._uAlphaFresnelCenterBias&&o.uniform1f(this._uAlphaFresnelCenterBias,r._alphaFresnel.centerBias),this._uAlphaFresnelEdgeColor&&o.uniform3fv(this._uAlphaFresnelEdgeColor,r._alphaFresnel.edgeColor),this._uAlphaFresnelCenterColor&&o.uniform3fv(this._uAlphaFresnelCenterColor,r._alphaFresnel.centerColor),this._uAlphaFresnelPower&&o.uniform1f(this._uAlphaFresnelPower,r._alphaFresnel.power)),r._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias&&o.uniform1f(this._uReflectivityFresnelEdgeBias,r._reflectivityFresnel.edgeBias),this._uReflectivityFresnelCenterBias&&o.uniform1f(this._uReflectivityFresnelCenterBias,r._reflectivityFresnel.centerBias),this._uReflectivityFresnelEdgeColor&&o.uniform3fv(this._uReflectivityFresnelEdgeColor,r._reflectivityFresnel.edgeColor),this._uReflectivityFresnelCenterColor&&o.uniform3fv(this._uReflectivityFresnelCenterColor,r._reflectivityFresnel.centerColor),this._uReflectivityFresnelPower&&o.uniform1f(this._uReflectivityFresnelPower,r._reflectivityFresnel.power)),r._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias&&o.uniform1f(this._uEmissiveFresnelEdgeBias,r._emissiveFresnel.edgeBias),this._uEmissiveFresnelCenterBias&&o.uniform1f(this._uEmissiveFresnelCenterBias,r._emissiveFresnel.centerBias),this._uEmissiveFresnelEdgeColor&&o.uniform3fv(this._uEmissiveFresnelEdgeColor,r._emissiveFresnel.edgeColor),this._uEmissiveFresnelCenterColor&&o.uniform3fv(this._uEmissiveFresnelCenterColor,r._emissiveFresnel.centerColor),this._uEmissiveFresnelPower&&o.uniform1f(this._uEmissiveFresnelPower,r._emissiveFresnel.power));break;case"MetallicMaterial":this._uBaseColor&&o.uniform3fv(this._uBaseColor,l.baseColor),this._uMaterialMetallic&&o.uniform1f(this._uMaterialMetallic,l.metallic),this._uMaterialRoughness&&o.uniform1f(this._uMaterialRoughness,l.roughness),this._uMaterialSpecularF0&&o.uniform1f(this._uMaterialSpecularF0,l.specularF0),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);const t=r._baseColorMap;t&&t._state.texture&&this._uBaseColorMap&&(a.bindTexture(this._uBaseColorMap,t._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uBaseColorMapMatrix&&o.uniformMatrix4fv(this._uBaseColorMapMatrix,!1,t._state.matrix));const s=r._metallicMap;s&&s._state.texture&&this._uMetallicMap&&(a.bindTexture(this._uMetallicMap,s._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicMapMatrix&&o.uniformMatrix4fv(this._uMetallicMapMatrix,!1,s._state.matrix));const n=r._roughnessMap;n&&n._state.texture&&this._uRoughnessMap&&(a.bindTexture(this._uRoughnessMap,n._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uRoughnessMapMatrix&&o.uniformMatrix4fv(this._uRoughnessMapMatrix,!1,n._state.matrix));const h=r._metallicRoughnessMap;h&&h._state.texture&&this._uMetallicRoughnessMap&&(a.bindTexture(this._uMetallicRoughnessMap,h._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uMetallicRoughnessMapMatrix&&o.uniformMatrix4fv(this._uMetallicRoughnessMapMatrix,!1,h._state.matrix)),(d=r._emissiveMap)&&d._state.texture&&this._uEmissiveMap&&(a.bindTexture(this._uEmissiveMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,d._state.matrix)),(p=r._occlusionMap)&&r._occlusionMap._state.texture&&this._uOcclusionMap&&(a.bindTexture(this._uOcclusionMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,p._state.matrix)),(_=r._alphaMap)&&_._state.texture&&this._uAlphaMap&&(a.bindTexture(this._uAlphaMap,_._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,_._state.matrix)),(f=r._normalMap)&&f._state.texture&&this._uNormalMap&&(a.bindTexture(this._uNormalMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,f._state.matrix));break;case"SpecularMaterial":this._uMaterialDiffuse&&o.uniform3fv(this._uMaterialDiffuse,l.diffuse),this._uMaterialSpecular&&o.uniform3fv(this._uMaterialSpecular,l.specular),this._uMaterialGlossiness&&o.uniform1f(this._uMaterialGlossiness,l.glossiness),this._uMaterialReflectivity&&o.uniform1f(this._uMaterialReflectivity,l.reflectivity),this._uMaterialEmissive&&o.uniform3fv(this._uMaterialEmissive,l.emissive),this._uAlphaModeCutoff&&o.uniform4f(this._uAlphaModeCutoff,1*l.alpha,1===l.alphaMode?1:0,l.alphaCutoff,0);const c=r._diffuseMap;c&&c._state.texture&&this._uDiffuseMap&&(a.bindTexture(this._uDiffuseMap,c._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uDiffuseMapMatrix&&o.uniformMatrix4fv(this._uDiffuseMapMatrix,!1,c._state.matrix));const u=r._specularMap;u&&u._state.texture&&this._uSpecularMap&&(a.bindTexture(this._uSpecularMap,u._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularMapMatrix&&o.uniformMatrix4fv(this._uSpecularMapMatrix,!1,u._state.matrix));const g=r._glossinessMap;g&&g._state.texture&&this._uGlossinessMap&&(a.bindTexture(this._uGlossinessMap,g._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uGlossinessMapMatrix&&o.uniformMatrix4fv(this._uGlossinessMapMatrix,!1,g._state.matrix));const m=r._specularGlossinessMap;var d,p,_,f;m&&m._state.texture&&this._uSpecularGlossinessMap&&(a.bindTexture(this._uSpecularGlossinessMap,m._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uSpecularGlossinessMapMatrix&&o.uniformMatrix4fv(this._uSpecularGlossinessMapMatrix,!1,m._state.matrix)),(d=r._emissiveMap)&&d._state.texture&&this._uEmissiveMap&&(a.bindTexture(this._uEmissiveMap,d._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uEmissiveMapMatrix&&o.uniformMatrix4fv(this._uEmissiveMapMatrix,!1,d._state.matrix)),(p=r._occlusionMap)&&p._state.texture&&this._uOcclusionMap&&(a.bindTexture(this._uOcclusionMap,p._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uOcclusionMapMatrix&&o.uniformMatrix4fv(this._uOcclusionMapMatrix,!1,p._state.matrix)),(_=r._alphaMap)&&_._state.texture&&this._uAlphaMap&&(a.bindTexture(this._uAlphaMap,_._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uAlphaMapMatrix&&o.uniformMatrix4fv(this._uAlphaMapMatrix,!1,_._state.matrix)),(f=r._normalMap)&&f._state.texture&&this._uNormalMap&&(a.bindTexture(this._uNormalMap,f._state.texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%i,e.bindTexture++,this._uNormalMapMatrix&&o.uniformMatrix4fv(this._uNormalMapMatrix,!1,f._state.matrix))}this._lastMaterialId=l.id}if(o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uModelNormalMatrix&&o.uniformMatrix4fv(this._uModelNormalMatrix,o.FALSE,t.worldNormalMatrix),this._uClippable&&o.uniform1i(this._uClippable,n.clippable),this._uColorize){const e=n.colorize,t=this._lastColorize;t[0]===e[0]&&t[1]===e[1]&&t[2]===e[2]&&t[3]===e[3]||(o.uniform4fv(this._uColorize,e),t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3])}o.uniform3fv(this._uOffset,n.offset),h.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,h.positionsDecodeMatrix),this._uUVDecodeMatrix&&o.uniformMatrix3fv(this._uUVDecodeMatrix,!1,h.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(h.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(h.normalsBuf),e.bindArray++),this._aUV&&(this._aUV.bindArrayBuffer(h.uvBuf),e.bindArray++),this._aColor&&(this._aColor.bindArrayBuffer(h.colorsBuf),e.bindArray++),this._aFlags&&(this._aFlags.bindArrayBuffer(h.flagsBuf),e.bindArray++),h.indicesBuf&&(h.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=h.id),h.indicesBuf?(o.drawElements(h.primitive,h.indicesBuf.numItems,h.indicesBuf.itemType,0),e.drawElements++):h.positions&&(o.drawArrays(o.TRIANGLES,0,h.positions.numItems),e.drawArrays++)},Pt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl,s=e._material,r=t._lightsState,o=t._sectionPlanesState,a=e._material._state;if(this._program=new J(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const n=this._program;this._uPositionsDecodeMatrix=n.getLocation("positionsDecodeMatrix"),this._uUVDecodeMatrix=n.getLocation("uvDecodeMatrix"),this._uModelMatrix=n.getLocation("modelMatrix"),this._uModelNormalMatrix=n.getLocation("modelNormalMatrix"),this._uViewMatrix=n.getLocation("viewMatrix"),this._uViewNormalMatrix=n.getLocation("viewNormalMatrix"),this._uProjMatrix=n.getLocation("projMatrix"),this._uGammaFactor=n.getLocation("gammaFactor"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[],this._uShadowViewMatrix=[],this._uShadowProjMatrix=[],t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=n.getLocation("logDepthBufFC"));const l=r.lights;let h;for(var c=0,u=l.length;c<u;c++){switch(h=l[c],h.type){case"ambient":this._uLightAmbient[c]=n.getLocation("lightAmbient");break;case"dir":this._uLightColor[c]=n.getLocation("lightColor"+c),this._uLightPos[c]=null,this._uLightDir[c]=n.getLocation("lightDir"+c);break;case"point":this._uLightColor[c]=n.getLocation("lightColor"+c),this._uLightPos[c]=n.getLocation("lightPos"+c),this._uLightDir[c]=null,this._uLightAttenuation[c]=n.getLocation("lightAttenuation"+c);break;case"spot":this._uLightColor[c]=n.getLocation("lightColor"+c),this._uLightPos[c]=n.getLocation("lightPos"+c),this._uLightDir[c]=n.getLocation("lightDir"+c),this._uLightAttenuation[c]=n.getLocation("lightAttenuation"+c)}h.castsShadow&&(this._uShadowViewMatrix[c]=n.getLocation("shadowViewMatrix"+c),this._uShadowProjMatrix[c]=n.getLocation("shadowProjMatrix"+c))}for(r.lightMaps.length>0&&(this._uLightMap="lightMap"),r.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),this._uSectionPlanes=[],c=0,u=o.sectionPlanes.length;c<u;c++)this._uSectionPlanes.push({active:n.getLocation("sectionPlaneActive"+c),pos:n.getLocation("sectionPlanePos"+c),dir:n.getLocation("sectionPlaneDir"+c)});switch(this._uPointSize=n.getLocation("pointSize"),a.type){case"LambertMaterial":this._uMaterialColor=n.getLocation("materialColor"),this._uMaterialEmissive=n.getLocation("materialEmissive"),this._uAlphaModeCutoff=n.getLocation("materialAlphaModeCutoff");break;case"PhongMaterial":this._uMaterialAmbient=n.getLocation("materialAmbient"),this._uMaterialDiffuse=n.getLocation("materialDiffuse"),this._uMaterialSpecular=n.getLocation("materialSpecular"),this._uMaterialEmissive=n.getLocation("materialEmissive"),this._uAlphaModeCutoff=n.getLocation("materialAlphaModeCutoff"),this._uMaterialShininess=n.getLocation("materialShininess"),s._ambientMap&&(this._uMaterialAmbientMap="ambientMap",this._uMaterialAmbientMapMatrix=n.getLocation("ambientMapMatrix")),s._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=n.getLocation("diffuseMapMatrix")),s._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=n.getLocation("specularMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=n.getLocation("emissiveMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=n.getLocation("alphaMapMatrix")),s._reflectivityMap&&(this._uReflectivityMap="reflectivityMap",this._uReflectivityMapMatrix=n.getLocation("reflectivityMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=n.getLocation("normalMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=n.getLocation("occlusionMapMatrix")),s._diffuseFresnel&&(this._uDiffuseFresnelEdgeBias=n.getLocation("diffuseFresnelEdgeBias"),this._uDiffuseFresnelCenterBias=n.getLocation("diffuseFresnelCenterBias"),this._uDiffuseFresnelEdgeColor=n.getLocation("diffuseFresnelEdgeColor"),this._uDiffuseFresnelCenterColor=n.getLocation("diffuseFresnelCenterColor"),this._uDiffuseFresnelPower=n.getLocation("diffuseFresnelPower")),s._specularFresnel&&(this._uSpecularFresnelEdgeBias=n.getLocation("specularFresnelEdgeBias"),this._uSpecularFresnelCenterBias=n.getLocation("specularFresnelCenterBias"),this._uSpecularFresnelEdgeColor=n.getLocation("specularFresnelEdgeColor"),this._uSpecularFresnelCenterColor=n.getLocation("specularFresnelCenterColor"),this._uSpecularFresnelPower=n.getLocation("specularFresnelPower")),s._alphaFresnel&&(this._uAlphaFresnelEdgeBias=n.getLocation("alphaFresnelEdgeBias"),this._uAlphaFresnelCenterBias=n.getLocation("alphaFresnelCenterBias"),this._uAlphaFresnelEdgeColor=n.getLocation("alphaFresnelEdgeColor"),this._uAlphaFresnelCenterColor=n.getLocation("alphaFresnelCenterColor"),this._uAlphaFresnelPower=n.getLocation("alphaFresnelPower")),s._reflectivityFresnel&&(this._uReflectivityFresnelEdgeBias=n.getLocation("reflectivityFresnelEdgeBias"),this._uReflectivityFresnelCenterBias=n.getLocation("reflectivityFresnelCenterBias"),this._uReflectivityFresnelEdgeColor=n.getLocation("reflectivityFresnelEdgeColor"),this._uReflectivityFresnelCenterColor=n.getLocation("reflectivityFresnelCenterColor"),this._uReflectivityFresnelPower=n.getLocation("reflectivityFresnelPower")),s._emissiveFresnel&&(this._uEmissiveFresnelEdgeBias=n.getLocation("emissiveFresnelEdgeBias"),this._uEmissiveFresnelCenterBias=n.getLocation("emissiveFresnelCenterBias"),this._uEmissiveFresnelEdgeColor=n.getLocation("emissiveFresnelEdgeColor"),this._uEmissiveFresnelCenterColor=n.getLocation("emissiveFresnelCenterColor"),this._uEmissiveFresnelPower=n.getLocation("emissiveFresnelPower"));break;case"MetallicMaterial":this._uBaseColor=n.getLocation("materialBaseColor"),this._uMaterialMetallic=n.getLocation("materialMetallic"),this._uMaterialRoughness=n.getLocation("materialRoughness"),this._uMaterialSpecularF0=n.getLocation("materialSpecularF0"),this._uMaterialEmissive=n.getLocation("materialEmissive"),this._uAlphaModeCutoff=n.getLocation("materialAlphaModeCutoff"),s._baseColorMap&&(this._uBaseColorMap="baseColorMap",this._uBaseColorMapMatrix=n.getLocation("baseColorMapMatrix")),s._metallicMap&&(this._uMetallicMap="metallicMap",this._uMetallicMapMatrix=n.getLocation("metallicMapMatrix")),s._roughnessMap&&(this._uRoughnessMap="roughnessMap",this._uRoughnessMapMatrix=n.getLocation("roughnessMapMatrix")),s._metallicRoughnessMap&&(this._uMetallicRoughnessMap="metallicRoughnessMap",this._uMetallicRoughnessMapMatrix=n.getLocation("metallicRoughnessMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=n.getLocation("emissiveMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=n.getLocation("occlusionMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=n.getLocation("alphaMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=n.getLocation("normalMapMatrix"));break;case"SpecularMaterial":this._uMaterialDiffuse=n.getLocation("materialDiffuse"),this._uMaterialSpecular=n.getLocation("materialSpecular"),this._uMaterialGlossiness=n.getLocation("materialGlossiness"),this._uMaterialReflectivity=n.getLocation("reflectivityFresnel"),this._uMaterialEmissive=n.getLocation("materialEmissive"),this._uAlphaModeCutoff=n.getLocation("materialAlphaModeCutoff"),s._diffuseMap&&(this._uDiffuseMap="diffuseMap",this._uDiffuseMapMatrix=n.getLocation("diffuseMapMatrix")),s._specularMap&&(this._uSpecularMap="specularMap",this._uSpecularMapMatrix=n.getLocation("specularMapMatrix")),s._glossinessMap&&(this._uGlossinessMap="glossinessMap",this._uGlossinessMapMatrix=n.getLocation("glossinessMapMatrix")),s._specularGlossinessMap&&(this._uSpecularGlossinessMap="materialSpecularGlossinessMap",this._uSpecularGlossinessMapMatrix=n.getLocation("materialSpecularGlossinessMapMatrix")),s._emissiveMap&&(this._uEmissiveMap="emissiveMap",this._uEmissiveMapMatrix=n.getLocation("emissiveMapMatrix")),s._occlusionMap&&(this._uOcclusionMap="occlusionMap",this._uOcclusionMapMatrix=n.getLocation("occlusionMapMatrix")),s._alphaMap&&(this._uAlphaMap="alphaMap",this._uAlphaMapMatrix=n.getLocation("alphaMapMatrix")),s._normalMap&&(this._uNormalMap="normalMap",this._uNormalMapMatrix=n.getLocation("normalMapMatrix"))}this._aPosition=n.getAttribute("position"),this._aNormal=n.getAttribute("normal"),this._aUV=n.getAttribute("uv"),this._aColor=n.getAttribute("color"),this._aFlags=n.getAttribute("flags"),this._uClippable=n.getLocation("clippable"),this._uColorize=n.getLocation("colorize"),this._uOffset=n.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize=new Float32Array(4),this._baseTextureUnit=0},Pt.prototype._bindProgram=function(e){const t=V.MAX_TEXTURE_UNITS,i=this._scene,s=i.canvas.gl,r=i._lightsState,o=i.camera.project;let a;const n=this._program;if(n.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastColorize[0]=-1,this._lastColorize[1]=-1,this._lastColorize[2]=-1,this._lastColorize[3]=-1,s.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}for(var l=0,h=r.lights.length;l<h;l++)if(a=r.lights[l],this._uLightAmbient[l])s.uniform4f(this._uLightAmbient[l],a.color[0],a.color[1],a.color[2],a.intensity);else if(this._uLightColor[l]&&s.uniform4f(this._uLightColor[l],a.color[0],a.color[1],a.color[2],a.intensity),this._uLightPos[l]&&(s.uniform3fv(this._uLightPos[l],a.pos),this._uLightAttenuation[l]&&s.uniform1f(this._uLightAttenuation[l],a.attenuation)),this._uLightDir[l]&&s.uniform3fv(this._uLightDir[l],a.dir),a.castsShadow){this._uShadowViewMatrix[l]&&s.uniformMatrix4fv(this._uShadowViewMatrix[l],!1,a.getShadowViewMatrix()),this._uShadowProjMatrix[l]&&s.uniformMatrix4fv(this._uShadowProjMatrix[l],!1,a.getShadowProjMatrix());const i=a.getShadowRenderBuf();i&&(n.bindTexture("shadowMap"+l,i.getTexture(),e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++)}r.lightMaps.length>0&&r.lightMaps[0].texture&&this._uLightMap&&(n.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(n.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor),this._baseTextureUnit=e.textureUnit};class Mt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._lightsState,s=function(e){const t=e._geometry._state.primitiveName;return!(!e._geometry._state.autoVertexNormals&&!e._geometry._state.normalsBuf||"triangles"!==t&&"triangle-strip"!==t&&"triangle-fan"!==t)}(e),r=t._sectionPlanesState.sectionPlanes.length>0,o=!!e._geometry._state.compressGeometry,a=e._state.billboard,n=e._state.stationary,l=[];if(l.push("// EmphasisFillShaderSource vertex shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&l.push("#extension GL_EXT_frag_depth : enable"),l.push("attribute vec3 position;"),l.push("uniform mat4 modelMatrix;"),l.push("uniform mat4 viewMatrix;"),l.push("uniform mat4 projMatrix;"),l.push("uniform vec4 colorize;"),l.push("uniform vec3 offset;"),o&&l.push("uniform mat4 positionsDecodeMatrix;"),t.logarithmicDepthBufferEnabled&&(l.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&l.push("varying float vFragDepth;")),r&&l.push("varying vec4 vWorldPosition;"),l.push("uniform vec4   lightAmbient;"),l.push("uniform vec4   fillColor;"),s){l.push("attribute vec3 normal;"),l.push("uniform mat4 modelNormalMatrix;"),l.push("uniform mat4 viewNormalMatrix;");for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];"ambient"!==t.type&&(l.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&l.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&l.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&l.push("uniform vec3 lightPos"+e+";"))}o&&(l.push("vec3 octDecode(vec2 oct) {"),l.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),l.push("    if (v.z < 0.0) {"),l.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),l.push("    }"),l.push("    return normalize(v);"),l.push("}"))}if(l.push("varying vec4 vColor;"),("spherical"===a||"cylindrical"===a)&&(l.push("void billboard(inout mat4 mat) {"),l.push("   mat[0][0] = 1.0;"),l.push("   mat[0][1] = 0.0;"),l.push("   mat[0][2] = 0.0;"),"spherical"===a&&(l.push("   mat[1][0] = 0.0;"),l.push("   mat[1][1] = 1.0;"),l.push("   mat[1][2] = 0.0;")),l.push("   mat[2][0] = 0.0;"),l.push("   mat[2][1] = 0.0;"),l.push("   mat[2][2] =1.0;"),l.push("}")),l.push("void main(void) {"),l.push("vec4 localPosition = vec4(position, 1.0); "),l.push("vec4 worldPosition;"),o&&l.push("localPosition = positionsDecodeMatrix * localPosition;"),s&&(o?l.push("vec4 localNormal = vec4(octDecode(normal.xy), 0.0); "):l.push("vec4 localNormal = vec4(normal, 0.0); "),l.push("mat4 modelNormalMatrix2 = modelNormalMatrix;"),l.push("mat4 viewNormalMatrix2 = viewNormalMatrix;")),l.push("mat4 viewMatrix2 = viewMatrix;"),l.push("mat4 modelMatrix2 = modelMatrix;"),n&&l.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===a||"cylindrical"===a?(l.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),l.push("billboard(modelMatrix2);"),l.push("billboard(viewMatrix2);"),l.push("billboard(modelViewMatrix);"),s&&(l.push("mat4 modelViewNormalMatrix =  viewNormalMatrix2 * modelNormalMatrix2;"),l.push("billboard(modelNormalMatrix2);"),l.push("billboard(viewNormalMatrix2);"),l.push("billboard(modelViewNormalMatrix);")),l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(l.push("worldPosition = modelMatrix2 * localPosition;"),l.push("worldPosition.xyz = worldPosition.xyz + offset;"),l.push("vec4 viewPosition  = viewMatrix2 * worldPosition; ")),s&&l.push("vec3 viewNormal = normalize((viewNormalMatrix2 * modelNormalMatrix2 * localNormal).xyz);"),l.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),l.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),l.push("float lambertian = 1.0;"),s)for(let e=0,t=i.lights.length;e<t;e++){const t=i.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?l.push("viewLightDir = normalize(lightDir"+e+");"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightDir"+e+", 0.0)).xyz);");else{if("point"!==t.type)continue;"view"===t.space?l.push("viewLightDir = normalize(lightPos"+e+" - viewPosition.xyz);"):l.push("viewLightDir = normalize((viewMatrix2 * vec4(lightPos"+e+", 0.0)).xyz);")}l.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),l.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}}return l.push("vColor = vec4(reflectedColor * fillColor.rgb, fillColor.a);"),r&&l.push("vWorldPosition = worldPosition;"),"points"===e._geometry._state.primitiveName&&l.push("gl_PointSize = pointSize;"),l.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?l.push("vFragDepth = 1.0 + clipPos.w;"):(l.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),l.push("clipPos.z *= clipPos.w;"))),l.push("gl_Position = clipPos;"),l.push("}"),l}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.sectionPlanes.length>0,o=[];if(o.push("// Lambertian drawing fragment shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(o.push("uniform float logDepthBufFC;"),o.push("varying float vFragDepth;")),s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push("  return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("varying vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)o.push("uniform bool sectionPlaneActive"+e+";"),o.push("uniform vec3 sectionPlanePos"+e+";"),o.push("uniform vec3 sectionPlaneDir"+e+";")}if(o.push("varying vec4 vColor;"),o.push("void main(void) {"),r){o.push("if (clippable) {"),o.push("  float dist = 0.0;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push("  if (dist > 0.0) { discard; }"),o.push("}")}return"points"===e._geometry._state.primitiveName&&(o.push("vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("float r = dot(cxy, cxy);"),o.push("if (r > 1.0) {"),o.push("   discard;"),o.push("}")),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s?o.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):o.push("gl_FragColor = vColor;"),o.push("}"),o}(e)}}const xt=new e({}),wt=u.vec3(),Et=function(e,t){this.id=xt.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Mt(t),this._allocate(t)},At={};Et.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.normalsBuf?"n":"",e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=At[t];return i||(i=new Et(t,e),At[t]=i,d.memory.programs++),i._useCount++,i},Et.prototype.put=function(){0==--this._useCount&&(xt.removeItem(this.id),this._program&&this._program.destroy(),delete At[this._hash],d.memory.programs--)},Et.prototype.webglContextRestored=function(){this._program=null},Et.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl,a=0===i?t._xrayMaterial._state:1===i?t._highlightMaterial._state:t._selectedMaterial._state,n=t._state,l=t._geometry._state,h=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,h?e.getRTCViewMatrix(n.rtcCenterHash,h):r.viewMatrix),o.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),n.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t],s=r.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,s?1:0),s){const s=i[t];o.uniform3fv(e.pos,h?O(s.dist,s.dir,h,wt):s.pos),o.uniform3fv(e.dir,s.dir)}}}}if(a.id!==this._lastMaterialId){const t=a.fillColor,i=a.backfaces;e.backfaces!==i&&(i?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=i),o.uniform4f(this._uFillColor,t[0],t[1],t[2],a.fillAlpha),this._lastMaterialId=a.id}o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uModelNormalMatrix&&o.uniformMatrix4fv(this._uModelNormalMatrix,o.FALSE,t.worldNormalMatrix),this._uClippable&&o.uniform1i(this._uClippable,n.clippable),o.uniform3fv(this._uOffset,n.offset),l.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,l.positionsDecodeMatrix),this._uUVDecodeMatrix&&o.uniformMatrix3fv(this._uUVDecodeMatrix,!1,l.uvDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(l.positionsBuf),e.bindArray++),this._aNormal&&(this._aNormal.bindArrayBuffer(l.normalsBuf),e.bindArray++),l.indicesBuf?(l.indicesBuf.bind(),e.bindArray++):l.positionsBuf,this._lastGeometryId=l.id),l.indicesBuf?(o.drawElements(l.primitive,l.indicesBuf.numItems,l.indicesBuf.itemType,0),e.drawElements++):l.positionsBuf&&(o.drawArrays(o.TRIANGLES,0,l.positionsBuf.numItems),e.drawArrays++)},Et.prototype._allocate=function(e){const t=e.scene,i=t._lightsState,s=t._sectionPlanesState,r=t.canvas.gl;if(this._program=new J(r,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const o=this._program;this._uPositionsDecodeMatrix=o.getLocation("positionsDecodeMatrix"),this._uModelMatrix=o.getLocation("modelMatrix"),this._uModelNormalMatrix=o.getLocation("modelNormalMatrix"),this._uViewMatrix=o.getLocation("viewMatrix"),this._uViewNormalMatrix=o.getLocation("viewNormalMatrix"),this._uProjMatrix=o.getLocation("projMatrix"),this._uLightAmbient=[],this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];for(let e=0,t=i.lights.length;e<t;e++)switch(i.lights[e].type){case"ambient":this._uLightAmbient[e]=o.getLocation("lightAmbient");break;case"dir":this._uLightColor[e]=o.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=o.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=o.getLocation("lightColor"+e),this._uLightPos[e]=o.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=o.getLocation("lightAttenuation"+e)}this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:o.getLocation("sectionPlaneActive"+e),pos:o.getLocation("sectionPlanePos"+e),dir:o.getLocation("sectionPlaneDir"+e)});this._uFillColor=o.getLocation("fillColor"),this._aPosition=o.getAttribute("position"),this._aNormal=o.getAttribute("normal"),this._uClippable=o.getLocation("clippable"),this._uGammaFactor=o.getLocation("gammaFactor"),this._uOffset=o.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=o.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Et.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t._lightsState,r=t.camera,o=r.project;if(this._program.bind(),e.useProgram++,e.textureUnit=0,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,this._lastIndicesBufId=null,i.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.normalMatrix),i.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];this._uLightAmbient[e]?i.uniform4f(this._uLightAmbient[e],t.color[0],t.color[1],t.color[2],t.intensity):(this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir))}this._uGammaFactor&&i.uniform1f(this._uGammaFactor,t.gammaFactor)};class Ct{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,a=[];return a.push("// Edges drawing vertex shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("attribute vec3 position;"),a.push("uniform mat4 modelMatrix;"),a.push("uniform mat4 viewMatrix;"),a.push("uniform mat4 projMatrix;"),a.push("uniform vec4 edgeColor;"),a.push("uniform vec3 offset;"),s&&a.push("uniform mat4 positionsDecodeMatrix;"),t.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("varying float vFragDepth;")),i&&a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vColor;"),("spherical"===r||"cylindrical"===r)&&(a.push("void billboard(inout mat4 mat) {"),a.push("   mat[0][0] = 1.0;"),a.push("   mat[0][1] = 0.0;"),a.push("   mat[0][2] = 0.0;"),"spherical"===r&&(a.push("   mat[1][0] = 0.0;"),a.push("   mat[1][1] = 1.0;"),a.push("   mat[1][2] = 0.0;")),a.push("   mat[2][0] = 0.0;"),a.push("   mat[2][1] = 0.0;"),a.push("   mat[2][2] =1.0;"),a.push("}")),a.push("void main(void) {"),a.push("vec4 localPosition = vec4(position, 1.0); "),a.push("vec4 worldPosition;"),s&&a.push("localPosition = positionsDecodeMatrix * localPosition;"),a.push("mat4 viewMatrix2 = viewMatrix;"),a.push("mat4 modelMatrix2 = modelMatrix;"),o&&a.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"===r||"cylindrical"===r?(a.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),a.push("billboard(modelMatrix2);"),a.push("billboard(viewMatrix2);"),a.push("billboard(modelViewMatrix);"),a.push("worldPosition = modelMatrix2 * localPosition;"),a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition = modelViewMatrix * localPosition;")):(a.push("worldPosition = modelMatrix2 * localPosition;"),a.push("worldPosition.xyz = worldPosition.xyz + offset;"),a.push("vec4 viewPosition  = viewMatrix2 * worldPosition; ")),a.push("vColor = edgeColor;"),i&&a.push("vWorldPosition = worldPosition;"),a.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?a.push("vFragDepth = 1.0 + clipPos.w;"):(a.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),a.push("clipPos.z *= clipPos.w;"))),a.push("gl_Position = clipPos;"),a.push("}"),a}(e),this.fragment=function(e){const t=e.scene,i=e.scene._sectionPlanesState,s=e.scene.gammaOutput,r=i.sectionPlanes.length>0,o=[];if(o.push("// Edges drawing fragment shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(o.push("uniform float logDepthBufFC;"),o.push("varying float vFragDepth;")),s&&(o.push("uniform float gammaFactor;"),o.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),o.push("  return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),o.push("}")),r){o.push("varying vec4 vWorldPosition;"),o.push("uniform bool clippable;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)o.push("uniform bool sectionPlaneActive"+e+";"),o.push("uniform vec3 sectionPlanePos"+e+";"),o.push("uniform vec3 sectionPlaneDir"+e+";")}if(o.push("varying vec4 vColor;"),o.push("void main(void) {"),r){o.push("if (clippable) {"),o.push("  float dist = 0.0;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)o.push("if (sectionPlaneActive"+e+") {"),o.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),o.push("}");o.push("  if (dist > 0.0) { discard; }"),o.push("}")}return t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s?o.push("gl_FragColor = linearToGamma(vColor, gammaFactor);"):o.push("gl_FragColor = vColor;"),o.push("}"),o}(e)}}const St=new e({}),Dt=u.vec3(),Lt=function(e,t){this.id=St.addItem({}),this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new Ct(t),this._allocate(t)},Bt={};Lt.get=function(e){const t=[e.scene.id,e.scene.gammaOutput?"go":"",e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Bt[t];return i||(i=new Lt(t,e),Bt[t]=i,d.memory.programs++),i._useCount++,i},Lt.prototype.put=function(){0==--this._useCount&&(St.removeItem(this.id),this._program&&this._program.destroy(),delete Bt[this._hash],d.memory.programs--)},Lt.prototype.webglContextRestored=function(){this._program=null},Lt.prototype.drawMesh=function(e,t,i){this._program||this._allocate(t);const s=this._scene,r=s.camera,o=s.canvas.gl;let a;const n=t._state,l=t._geometry,h=l._state,c=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),o.uniformMatrix4fv(this._uViewMatrix,!1,c?e.getRTCViewMatrix(n.rtcCenterHash,c):r.viewMatrix),n.clippable){const e=s._sectionPlanesState.sectionPlanes.length;if(e>0){const i=s._sectionPlanesState.sectionPlanes,r=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t],s=r.sectionPlanesActivePerLayer[t];if(o.uniform1i(e.active,s?1:0),s){const s=i[t];o.uniform3fv(e.pos,c?O(s.dist,s.dir,c,Dt):s.pos),o.uniform3fv(e.dir,s.dir)}}}}switch(i){case 0:a=t._xrayMaterial._state;break;case 1:a=t._highlightMaterial._state;break;case 2:a=t._selectedMaterial._state;break;case 3:default:a=t._edgeMaterial._state}if(a.id!==this._lastMaterialId){const t=a.backfaces;if(e.backfaces!==t&&(t?o.disable(o.CULL_FACE):o.enable(o.CULL_FACE),e.backfaces=t),e.lineWidth!==a.edgeWidth&&(o.lineWidth(a.edgeWidth),e.lineWidth=a.edgeWidth),this._uEdgeColor){const e=a.edgeColor,t=a.edgeAlpha;o.uniform4f(this._uEdgeColor,e[0],e[1],e[2],t)}this._lastMaterialId=a.id}let u;o.uniformMatrix4fv(this._uModelMatrix,o.FALSE,t.worldMatrix),this._uClippable&&o.uniform1i(this._uClippable,n.clippable),o.uniform3fv(this._uOffset,n.offset),h.primitive===o.TRIANGLES?u=l._getEdgeIndices():h.primitive===o.LINES&&(u=h.indicesBuf),u&&(h.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,h.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(h.positionsBuf,h.compressGeometry?o.UNSIGNED_SHORT:o.FLOAT),e.bindArray++),u.bind(),e.bindArray++,this._lastGeometryId=h.id),o.drawElements(o.LINES,u.numItems,u.itemType,0),e.drawElements++)},Lt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program=new J(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const r=this._program;this._uPositionsDecodeMatrix=r.getLocation("positionsDecodeMatrix"),this._uModelMatrix=r.getLocation("modelMatrix"),this._uViewMatrix=r.getLocation("viewMatrix"),this._uProjMatrix=r.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=s.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:r.getLocation("sectionPlaneActive"+e),pos:r.getLocation("sectionPlanePos"+e),dir:r.getLocation("sectionPlaneDir"+e)});this._uEdgeColor=r.getLocation("edgeColor"),this._aPosition=r.getAttribute("position"),this._uClippable=r.getLocation("clippable"),this._uGammaFactor=r.getLocation("gammaFactor"),this._uOffset=r.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=r.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Lt.prototype._bindProgram=function(e){const t=this._program,i=this._scene,s=i.canvas.gl,r=i.camera.project;if(t.bind(),e.useProgram++,this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),i.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor)};class Tt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,a=[];return a.push("// Mesh picking vertex shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("attribute vec3 position;"),a.push("uniform mat4 modelMatrix;"),a.push("uniform mat4 viewMatrix;"),a.push("uniform mat4 projMatrix;"),a.push("varying vec4 vViewPosition;"),a.push("uniform vec3 offset;"),s&&a.push("uniform mat4 positionsDecodeMatrix;"),i&&a.push("varying vec4 vWorldPosition;"),t.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("varying float vFragDepth;")),"spherical"!==r&&"cylindrical"!==r||(a.push("void billboard(inout mat4 mat) {"),a.push("   mat[0][0] = 1.0;"),a.push("   mat[0][1] = 0.0;"),a.push("   mat[0][2] = 0.0;"),"spherical"===r&&(a.push("   mat[1][0] = 0.0;"),a.push("   mat[1][1] = 1.0;"),a.push("   mat[1][2] = 0.0;")),a.push("   mat[2][0] = 0.0;"),a.push("   mat[2][1] = 0.0;"),a.push("   mat[2][2] =1.0;"),a.push("}")),a.push("void main(void) {"),a.push("vec4 localPosition = vec4(position, 1.0); "),s&&a.push("localPosition = positionsDecodeMatrix * localPosition;"),a.push("mat4 viewMatrix2 = viewMatrix;"),a.push("mat4 modelMatrix2 = modelMatrix;"),o&&a.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"!==r&&"cylindrical"!==r||(a.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),a.push("billboard(modelMatrix2);"),a.push("billboard(viewMatrix2);")),a.push("   vec4 worldPosition = modelMatrix2 * localPosition;"),a.push("   worldPosition.xyz = worldPosition.xyz + offset;"),a.push("   vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&a.push("   vWorldPosition = worldPosition;"),a.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?a.push("vFragDepth = 1.0 + clipPos.w;"):(a.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),a.push("clipPos.z *= clipPos.w;"))),a.push("gl_Position = clipPos;"),a.push("}"),a}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.sectionPlanes.length>0,r=[];if(r.push("// Mesh picking fragment shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(r.push("uniform float logDepthBufFC;"),r.push("varying float vFragDepth;")),r.push("uniform vec4 pickColor;"),s){r.push("uniform bool clippable;"),r.push("varying vec4 vWorldPosition;");for(var o=0;o<i.sectionPlanes.length;o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("void main(void) {"),s){for(r.push("if (clippable) {"),r.push("  float dist = 0.0;"),o=0;o<i.sectionPlanes.length;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push("   dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push("  if (dist > 0.0) { discard; }"),r.push("}")}return t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("   gl_FragColor = pickColor; "),r.push("}"),r}(e)}}const Rt=u.vec3(),Ft=function(e,t){this._hash=e,this._shaderSource=new Tt(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Nt={};Ft.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Nt[t];if(!i){if(i=new Ft(t,e),i.errors)return console.log(i.errors.join("\n")),null;Nt[t]=i,d.memory.programs++}return i._useCount++,i},Ft.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Nt[this._hash],d.memory.programs--)},Ft.prototype.webglContextRestored=function(){this._program=null},Ft.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,a=t._geometry._state,n=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uViewMatrix,!1,n?e.getRTCPickViewMatrix(r.rtcCenterHash,n):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t],i=o.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=r[t];s.uniform3fv(e.pos,n?O(i.dist,i.dir,n,Rt):i.pos),s.uniform3fv(e.dir,i.dir)}}}}if(o.id!==this._lastMaterialId){const t=o.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=o.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=o.id}s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),s.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),a.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,a.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(a.positionsBuf,a.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),a.indicesBuf&&(a.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=a.id);var l=t._state.pickID;const h=l>>24&255,c=l>>16&255,u=l>>8&255,d=255&l;s.uniform4f(this._uPickColor,d/255,u/255,c/255,h/255),a.indicesBuf?(s.drawElements(a.primitive,a.indicesBuf.numItems,a.indicesBuf.itemType,0),e.drawElements++):a.positions&&s.drawArrays(s.TRIANGLES,0,a.positions.numItems)},Ft.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new J(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uPickColor=s.getLocation("pickColor"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastGeometryId=null},Ft.prototype._bindProgram=function(e){const t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),e.useProgram++,t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastGeometryId=null};class It{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry;e._state.billboard,e._state.stationary;const r=[];return r.push("// Surface picking vertex shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("attribute vec3 position;"),r.push("attribute vec4 color;"),r.push("uniform mat4 modelMatrix;"),r.push("uniform mat4 viewMatrix;"),r.push("uniform mat4 projMatrix;"),r.push("uniform vec3 offset;"),i&&(r.push("uniform bool clippable;"),r.push("varying vec4 vWorldPosition;")),t.logarithmicDepthBufferEnabled&&(r.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("varying float vFragDepth;")),r.push("varying vec4 vColor;"),s&&r.push("uniform mat4 positionsDecodeMatrix;"),r.push("void main(void) {"),r.push("vec4 localPosition = vec4(position, 1.0); "),s&&r.push("localPosition = positionsDecodeMatrix * localPosition;"),r.push("   vec4 worldPosition = modelMatrix * localPosition; "),r.push("   worldPosition.xyz = worldPosition.xyz + offset;"),r.push("   vec4 viewPosition = viewMatrix * worldPosition;"),i&&r.push("   vWorldPosition = worldPosition;"),r.push("   vColor = color;"),r.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?r.push("vFragDepth = 1.0 + clipPos.w;"):(r.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),r.push("clipPos.z *= clipPos.w;"))),r.push("gl_Position = clipPos;"),r.push("}"),r}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.sectionPlanes.length>0,r=[];if(r.push("// Surface picking fragment shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),r.push("varying vec4 vColor;"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(r.push("uniform float logDepthBufFC;"),r.push("varying float vFragDepth;")),s){r.push("uniform bool clippable;"),r.push("varying vec4 vWorldPosition;");for(let e=0;e<i.sectionPlanes.length;e++)r.push("uniform bool sectionPlaneActive"+e+";"),r.push("uniform vec3 sectionPlanePos"+e+";"),r.push("uniform vec3 sectionPlaneDir"+e+";")}if(r.push("void main(void) {"),s){r.push("if (clippable) {"),r.push("  float dist = 0.0;");for(let e=0;e<i.sectionPlanes.length;e++)r.push("if (sectionPlaneActive"+e+") {"),r.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),r.push("}");r.push("  if (dist > 0.0) { discard; }"),r.push("}")}return t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("   gl_FragColor = vColor;"),r.push("}"),r}(e)}}const Ot=u.vec3(),kt=function(e,t){this._hash=e,this._scene=t.scene,this._useCount=0,this._shaderSource=new It(t),this._allocate(t)},Vt={};kt.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.compressGeometry?"cp":"",e._state.hash].join(";");let i=Vt[t];if(!i){if(i=new kt(t,e),i.errors)return console.log(i.errors.join("\n")),null;Vt[t]=i,d.memory.programs++}return i._useCount++,i},kt.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Vt[this._hash],d.memory.programs--)},kt.prototype.webglContextRestored=function(){this._program=null},kt.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._state,o=t._material._state,a=t._geometry,n=t._geometry._state,l=t.rtcCenter,h=o.backfaces,c=o.frontface,u=i.camera.project,d=a._getPickTrianglePositions(),p=a._getPickTriangleColors();if(this._program.bind(),e.useProgram++,i.logarithmicDepthBufferEnabled){const e=2/(Math.log(u.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}if(s.uniformMatrix4fv(this._uViewMatrix,!1,l?e.getRTCPickViewMatrix(r.rtcCenterHash,l):e.pickViewMatrix),r.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t],i=o.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=r[t];s.uniform3fv(e.pos,l?O(i.dist,i.dir,l,Ot):i.pos),s.uniform3fv(e.dir,i.dir)}}}}s.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),i.logarithmicDepthBufferEnabled&&s.uniform1f(this._uZFar,i.camera.project.far),e.backfaces!==h&&(h?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=h),e.frontface!==c&&(c?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=c),s.uniformMatrix4fv(this._uModelMatrix,!1,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),this._uPositionsDecodeMatrix?(s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,n.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(d,n.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT)):this._aPosition.bindArrayBuffer(d),p.bind(),s.enableVertexAttribArray(this._aColor.location),s.vertexAttribPointer(this._aColor.location,p.itemSize,p.itemType,!0,0,0),s.drawArrays(n.primitive,0,d.numItems/3)},kt.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new J(i,this._shaderSource),this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aColor=s.getAttribute("color"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))};class jt{constructor(e){this.vertex=function(e){const t=e.scene,i=t._sectionPlanesState.sectionPlanes.length>0,s=!!e._geometry._state.compressGeometry,r=e._state.billboard,o=e._state.stationary,a=[];return a.push("// Mesh occlusion vertex shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("attribute vec3 position;"),a.push("uniform mat4 modelMatrix;"),a.push("uniform mat4 viewMatrix;"),a.push("uniform mat4 projMatrix;"),a.push("uniform vec3 offset;"),s&&a.push("uniform mat4 positionsDecodeMatrix;"),i&&a.push("varying vec4 vWorldPosition;"),t.logarithmicDepthBufferEnabled&&(a.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("varying float vFragDepth;")),"spherical"!==r&&"cylindrical"!==r||(a.push("void billboard(inout mat4 mat) {"),a.push("   mat[0][0] = 1.0;"),a.push("   mat[0][1] = 0.0;"),a.push("   mat[0][2] = 0.0;"),"spherical"===r&&(a.push("   mat[1][0] = 0.0;"),a.push("   mat[1][1] = 1.0;"),a.push("   mat[1][2] = 0.0;")),a.push("   mat[2][0] = 0.0;"),a.push("   mat[2][1] = 0.0;"),a.push("   mat[2][2] =1.0;"),a.push("}")),a.push("void main(void) {"),a.push("vec4 localPosition = vec4(position, 1.0); "),s&&a.push("localPosition = positionsDecodeMatrix * localPosition;"),a.push("mat4 viewMatrix2 = viewMatrix;"),a.push("mat4 modelMatrix2 = modelMatrix;"),o&&a.push("viewMatrix2[3][0] = viewMatrix2[3][1] = viewMatrix2[3][2] = 0.0;"),"spherical"!==r&&"cylindrical"!==r||(a.push("mat4 modelViewMatrix = viewMatrix2 * modelMatrix2;"),a.push("billboard(modelMatrix2);"),a.push("billboard(viewMatrix2);")),a.push("   vec4 worldPosition = modelMatrix2 * localPosition;"),a.push("   worldPosition.xyz = worldPosition.xyz + offset;"),a.push("   vec4 viewPosition = viewMatrix2 * worldPosition;"),i&&a.push("   vWorldPosition = worldPosition;"),a.push("vec4 clipPos = projMatrix * viewPosition;"),t.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?a.push("vFragDepth = 1.0 + clipPos.w;"):(a.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),a.push("clipPos.z *= clipPos.w;"))),a.push("gl_Position = clipPos;"),a.push("}"),a}(e),this.fragment=function(e){const t=e.scene,i=t._sectionPlanesState,s=i.sectionPlanes.length>0,r=[];if(r.push("// Mesh occlusion fragment shader"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("#extension GL_EXT_frag_depth : enable"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(r.push("uniform float logDepthBufFC;"),r.push("varying float vFragDepth;")),s){r.push("uniform bool clippable;"),r.push("varying vec4 vWorldPosition;");for(var o=0;o<i.sectionPlanes.length;o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("void main(void) {"),s){for(r.push("if (clippable) {"),r.push("  float dist = 0.0;"),o=0;o<i.sectionPlanes.length;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push("   dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push("  if (dist > 0.0) { discard; }"),r.push("}")}return r.push("   gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),t.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&r.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),r.push("}"),r}(e)}}const zt=u.vec3(),Ut=function(e,t){this._hash=e,this._shaderSource=new jt(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Gt={};Ut.get=function(e){const t=[e.scene.canvas.canvas.id,e.scene._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let i=Gt[t];if(!i){if(i=new Ut(t,e),i.errors)return console.log(i.errors.join("\n")),null;Gt[t]=i,d.memory.programs++}return i._useCount++,i},Ut.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Gt[this._hash],d.memory.programs--)},Ut.prototype.webglContextRestored=function(){this._program=null},Ut.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene,s=i.canvas.gl,r=t._material._state,o=t._state,a=t._geometry._state,n=t.rtcCenter;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),r.id!==this._lastMaterialId){const t=r.backfaces;e.backfaces!==t&&(t?s.disable(s.CULL_FACE):s.enable(s.CULL_FACE),e.backfaces=t);const i=r.frontface;e.frontface!==i&&(i?s.frontFace(s.CCW):s.frontFace(s.CW),e.frontface=i),this._lastMaterialId=r.id}const l=i.camera;if(s.uniformMatrix4fv(this._uViewMatrix,!1,n?e.getRTCViewMatrix(o.rtcCenterHash,n):l.viewMatrix),o.clippable){const e=i._sectionPlanesState.sectionPlanes.length;if(e>0){const r=i._sectionPlanesState.sectionPlanes,o=t.renderFlags;for(let t=0;t<e;t++){const e=this._uSectionPlanes[t],i=o.sectionPlanesActivePerLayer[t];if(s.uniform1i(e.active,i?1:0),i){const i=r[t];s.uniform3fv(e.pos,n?O(i.dist,i.dir,n,zt):i.pos),s.uniform3fv(e.dir,i.dir)}}}}s.uniformMatrix4fv(this._uProjMatrix,!1,l._project._state.matrix),s.uniformMatrix4fv(this._uModelMatrix,s.FALSE,t.worldMatrix),this._uClippable&&s.uniform1i(this._uClippable,t._state.clippable),s.uniform3fv(this._uOffset,t._state.offset),a.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,a.positionsDecodeMatrix),this._aPosition&&(this._aPosition.bindArrayBuffer(a.positionsBuf,a.compressGeometry?s.UNSIGNED_SHORT:s.FLOAT),e.bindArray++),a.indicesBuf&&(a.indicesBuf.bind(),e.bindArray++),this._lastGeometryId=a.id),a.indicesBuf?(s.drawElements(a.primitive,a.indicesBuf.numItems,a.indicesBuf.itemType,0),e.drawElements++):a.positions&&s.drawArrays(s.TRIANGLES,0,a.positions.numItems)},Ut.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new J(i,this._shaderSource),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),t.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC")),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Ut.prototype._bindProgram=function(e){const t=this._scene,i=t.camera.project,s=t.canvas.gl;if(this._program.bind(),e.useProgram++,s.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null};class Xt{constructor(e){this.vertex=function(e){const t=e.scene._sectionPlanesState.sectionPlanes.length>0,i=!!e._geometry._state.compressGeometry,s=[];return s.push("// Mesh shadow vertex shader"),s.push("attribute vec3 position;"),s.push("uniform mat4 modelMatrix;"),s.push("uniform mat4 shadowViewMatrix;"),s.push("uniform mat4 shadowProjMatrix;"),s.push("uniform vec3 offset;"),i&&s.push("uniform mat4 positionsDecodeMatrix;"),t&&s.push("varying vec4 vWorldPosition;"),s.push("void main(void) {"),s.push("vec4 localPosition = vec4(position, 1.0); "),s.push("vec4 worldPosition;"),i&&s.push("localPosition = positionsDecodeMatrix * localPosition;"),s.push("worldPosition = modelMatrix * localPosition;"),s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition  = shadowViewMatrix * worldPosition; "),t&&s.push("vWorldPosition = worldPosition;"),s.push("   gl_Position = shadowProjMatrix * viewPosition;"),s.push("}"),s}(e),this.fragment=function(e){const t=e.scene;t.canvas.gl;const i=t._sectionPlanesState,s=i.sectionPlanes.length>0,r=[];if(r.push("// Mesh shadow fragment shader"),r.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),r.push("precision highp float;"),r.push("precision highp int;"),r.push("#else"),r.push("precision mediump float;"),r.push("precision mediump int;"),r.push("#endif"),s){r.push("uniform bool clippable;"),r.push("varying vec4 vWorldPosition;");for(var o=0;o<i.sectionPlanes.length;o++)r.push("uniform bool sectionPlaneActive"+o+";"),r.push("uniform vec3 sectionPlanePos"+o+";"),r.push("uniform vec3 sectionPlaneDir"+o+";")}if(r.push("vec4 encodeFloat( const in float depth ) {"),r.push("  const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),r.push("  const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),r.push("  vec4 comp = fract(depth * bitShift);"),r.push("  comp -= comp.xxyz * bitMask;"),r.push("  return comp;"),r.push("}"),r.push("void main(void) {"),s){for(r.push("if (clippable) {"),r.push("  float dist = 0.0;"),o=0;o<i.sectionPlanes.length;o++)r.push("if (sectionPlaneActive"+o+") {"),r.push("   dist += clamp(dot(-sectionPlaneDir"+o+".xyz, vWorldPosition.xyz - sectionPlanePos"+o+".xyz), 0.0, 1000.0);"),r.push("}");r.push("  if (dist > 0.0) { discard; }"),r.push("}")}return r.push("gl_FragColor = encodeFloat(gl_FragCoord.z);"),r.push("}"),r}(e)}}const Ht=function(e,t){this._hash=e,this._shaderSource=new Xt(t),this._scene=t.scene,this._useCount=0,this._allocate(t)},Wt={};Ht.get=function(e){const t=e.scene,i=[t.canvas.canvas.id,t._sectionPlanesState.getHash(),e._geometry._state.hash,e._state.hash].join(";");let s=Wt[i];if(!s){if(s=new Ht(i,e),s.errors)return console.log(s.errors.join("\n")),null;Wt[i]=s,d.memory.programs++}return s._useCount++,s},Ht.prototype.put=function(){0==--this._useCount&&(this._program&&this._program.destroy(),delete Wt[this._hash],d.memory.programs--)},Ht.prototype.webglContextRestored=function(){this._program=null},Ht.prototype.drawMesh=function(e,t){this._program||this._allocate(t);const i=this._scene.canvas.gl,s=t._material._state,r=t._geometry._state;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.id!==this._lastMaterialId){const t=s.backfaces;e.backfaces!==t&&(t?i.disable(i.CULL_FACE):i.enable(i.CULL_FACE),e.backfaces=t);const r=s.frontface;e.frontface!==r&&(r?i.frontFace(i.CCW):i.frontFace(i.CW),e.frontface=r),e.lineWidth!==s.lineWidth&&(i.lineWidth(s.lineWidth),e.lineWidth=s.lineWidth),this._uPointSize&&i.uniform1i(this._uPointSize,s.pointSize),this._lastMaterialId=s.id}if(i.uniformMatrix4fv(this._uModelMatrix,i.FALSE,t.worldMatrix),r.combineGeometry){const s=t.vertexBufs;s.id!==this._lastVertexBufsId&&(s.positionsBuf&&this._aPosition&&(this._aPosition.bindArrayBuffer(s.positionsBuf,s.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),this._lastVertexBufsId=s.id)}this._uClippable&&i.uniform1i(this._uClippable,t._state.clippable),i.uniform3fv(this._uOffset,t._state.offset),r.id!==this._lastGeometryId&&(this._uPositionsDecodeMatrix&&i.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,r.positionsDecodeMatrix),r.combineGeometry?r.indicesBufCombined&&(r.indicesBufCombined.bind(),e.bindArray++):(this._aPosition&&(this._aPosition.bindArrayBuffer(r.positionsBuf,r.compressGeometry?i.UNSIGNED_SHORT:i.FLOAT),e.bindArray++),r.indicesBuf&&(r.indicesBuf.bind(),e.bindArray++)),this._lastGeometryId=r.id),r.combineGeometry?r.indicesBufCombined&&(i.drawElements(r.primitive,r.indicesBufCombined.numItems,r.indicesBufCombined.itemType,0),e.drawElements++):r.indicesBuf?(i.drawElements(r.primitive,r.indicesBuf.numItems,r.indicesBuf.itemType,0),e.drawElements++):r.positions&&(i.drawArrays(i.TRIANGLES,0,r.positions.numItems),e.drawArrays++)},Ht.prototype._allocate=function(e){const t=e.scene,i=t.canvas.gl;if(this._program=new J(i,this._shaderSource),this._scene=t,this._useCount=0,this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uModelMatrix=s.getLocation("modelMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes={};for(let e=0,i=t._sectionPlanesState.sectionPlanes.length;e<i;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._uClippable=s.getLocation("clippable"),this._uOffset=s.getLocation("offset"),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null},Ht.prototype._bindProgram=function(e){this._program||this._allocate(mesh);const t=this._scene,i=t.canvas.gl,s=t._sectionPlanesState;if(this._program.bind(),e.useProgram++,i.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),i.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastMaterialId=null,this._lastVertexBufsId=null,this._lastGeometryId=null,s.sectionPlanes.length>0){let e,t,r,o,a;for(let n=0,l=this._uSectionPlanes.length;n<l;n++)e=this._uSectionPlanes[n],t=e.active,r=s.sectionPlanes[n],t&&i.uniform1i(t,r.active),o=e.pos,o&&i.uniform3fv(e.pos,r.pos),a=e.dir,a&&i.uniform3fv(e.dir,r.dir)}};class Yt{constructor(){this.visibleLayers=[],this.sectionPlanesActivePerLayer=[],this.reset()}reset(){this.culled=!1,this.sectioned=!1,this.numLayers=0,this.numVisibleLayers=0,this.colorOpaque=!1,this.colorTransparent=!1,this.edgesOpaque=!1,this.edgesTransparent=!1,this.xrayedSilhouetteOpaque=!1,this.xrayedEdgesOpaque=!1,this.xrayedSilhouetteTransparent=!1,this.xrayedEdgesTransparent=!1,this.highlightedSilhouetteOpaque=!1,this.highlightedEdgesOpaque=!1,this.highlightedSilhouetteTransparent=!1,this.highlightedEdgesTransparent=!1,this.selectedSilhouetteOpaque=!1,this.selectedEdgesOpaque=!1,this.selectedSilhouetteTransparent=!1,this.selectedEdgesTransparent=!1}}const qt=u.OBB3(),Kt=u.vec4(),Zt=u.vec4(),Qt=u.vec4(),$t=u.vec3([1,0,0]),Jt=u.vec3([0,1,0]),ei=u.vec3([0,0,1]),ti=u.vec3(3),ii=u.vec3(3),si=u.identityMat4();class ri extends A{get type(){return"Mesh"}constructor(e,t={}){if(super(e,t),this.originalSystemId=t.originalSystemId||this.id,this.renderFlags=new Yt,this._state=new me({visible:!0,culled:!1,pickable:null,clippable:null,collidable:null,castsShadow:null,receivesShadow:null,xrayed:!1,highlighted:!1,selected:!1,edges:!1,stationary:!!t.stationary,billboard:this._checkBillboard(t.billboard),layer:null,colorize:null,pickID:this.scene._renderer.getPickID(this),drawHash:"",pickHash:"",offset:u.vec3(),rtcCenter:null,rtcCenterHash:null}),this._drawRenderer=null,this._shadowRenderer=null,this._emphasisFillRenderer=null,this._emphasisEdgesRenderer=null,this._pickMeshRenderer=null,this._pickTriangleRenderer=null,this._occlusionRenderer=null,this._geometry=t.geometry?this._checkComponent2(["ReadableGeometry","VBOGeometry"],t.geometry):this.scene.geometry,this._material=t.material?this._checkComponent2(["PhongMaterial","MetallicMaterial","SpecularMaterial","LambertMaterial"],t.material):this.scene.material,this._xrayMaterial=t.xrayMaterial?this._checkComponent("EmphasisMaterial",t.xrayMaterial):this.scene.xrayMaterial,this._highlightMaterial=t.highlightMaterial?this._checkComponent("EmphasisMaterial",t.highlightMaterial):this.scene.highlightMaterial,this._selectedMaterial=t.selectedMaterial?this._checkComponent("EmphasisMaterial",t.selectedMaterial):this.scene.selectedMaterial,this._edgeMaterial=t.edgeMaterial?this._checkComponent("EdgeMaterial",t.edgeMaterial):this.scene.edgeMaterial,this._parentNode=null,this._aabb=null,this._aabbDirty=!0,this._numTriangles=this._geometry?this._geometry.numTriangles:0,this.scene._aabbDirty=!0,this._scale=u.vec3(),this._quaternion=u.identityQuaternion(),this._rotation=u.vec3(),this._position=u.vec3(),this._worldMatrix=u.identityMat4(),this._worldNormalMatrix=u.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0,t.rtcCenter&&(this._state.rtcCenter=u.vec3(t.rtcCenter),this._state.rtcCenterHash=t.rtcCenter.join()),t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.layer=t.layer,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'"),this._parentNode=e}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this),this._parentNode=t.parent);this.compile()}get isMesh(){return!0}get parent(){return this._parentNode}_checkBillboard(e){return"spherical"!==(e=e||"none")&&"cylindrical"!==e&&"none"!==e&&(this.error("Unsupported value for 'billboard': "+e+" - accepted values are 'spherical', 'cylindrical' and 'none' - defaulting to 'none'."),e="none"),e}compile(){const e=this._makeDrawHash();this._state.drawHash!==e&&(this._state.drawHash=e,this._putDrawRenderers(),this._drawRenderer=Pt.get(this),this._emphasisFillRenderer=Et.get(this),this._emphasisEdgesRenderer=Lt.get(this));const t=this._makePickHash();this._state.pickHash!==t&&(this._state.pickHash=t,this._putPickRenderers(),this._pickMeshRenderer=Ft.get(this));const i=this._makeOcclusionHash();this._state.occlusionHash!==i&&(this._state.occlusionHash=i,this._putOcclusionRenderer(),this._occlusionRenderer=Ut.get(this))}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0,this._worldNormalMatrixDirty=!0}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)u.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_buildWorldNormalMatrix(){this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldNormalMatrix||(this._worldNormalMatrix=u.mat4()),u.transposeMat4(this._worldMatrix,this._worldNormalMatrix),u.inverseMat4(this._worldNormalMatrix),this._worldNormalMatrixDirty=!1}_setAABBDirty(){if(this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){this.scene._aabbDirty=!0,this._aabb||(this._aabb=u.AABB3()),this._buildAABB(this.worldMatrix,this._aabb),this._aabbDirty=!1}_webglContextRestored(){this._drawRenderer&&this._drawRenderer.webglContextRestored(),this._shadowRenderer&&this._shadowRenderer.webglContextRestored(),this._emphasisFillRenderer&&this._emphasisFillRenderer.webglContextRestored(),this._emphasisEdgesRenderer&&this._emphasisEdgesRenderer.webglContextRestored(),this._pickMeshRenderer&&this._pickMeshRenderer.webglContextRestored(),this._pickTriangleRenderer&&this._pickMeshRenderer.webglContextRestored(),this._occlusionRenderer&&this._occlusionRenderer.webglContextRestored()}_makeDrawHash(){const e=this.scene,t=[e.canvas.canvas.id,(e.gammaInput?"gi;":";")+(e.gammaOutput?"go":""),e._lightsState.getHash(),e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),i.receivesShadow&&t.push("/rs"),t.push(";"),t.join("")}_makePickHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}_makeOcclusionHash(){const e=this.scene,t=[e.canvas.canvas.id,e._sectionPlanesState.getHash()],i=this._state;return i.stationary&&t.push("/s"),"none"===i.billboard?t.push("/n"):"spherical"===i.billboard?t.push("/s"):"cylindrical"===i.billboard&&t.push("/c"),t.push(";"),t.join("")}_buildAABB(e,t){u.transformOBB3(e,this._geometry.obb,qt),u.OBB3ToAABB3(qt,t);const i=this._state.offset;if(t[0]+=i[0],t[1]+=i[1],t[2]+=i[2],t[3]+=i[0],t[4]+=i[1],t[5]+=i[2],this._state.rtcCenter){const e=this._state.rtcCenter;t[0]+=e[0],t[1]+=e[1],t[2]+=e[2],t[3]+=e[0],t[4]+=e[1],t[5]+=e[2]}}get geometry(){return this._geometry}get material(){return this._material}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),u.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),u.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this.__localMatrix||(this.__localMatrix=u.identityMat4()),this.__localMatrix.set(e||si),u.decomposeMat4(this.__localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this.__localMatrix||(this.__localMatrix=u.identityMat4()),u.composeMat4(this._position,this._quaternion,this._scale,this.__localMatrix),this._localMatrixDirty=!1),this.__localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrixDirty&&this._buildWorldNormalMatrix(),this._worldNormalMatrix}rotate(e,t){return Kt[0]=e[0],Kt[1]=e[1],Kt[2]=e[2],Kt[3]=t*u.DEGTORAD,u.angleAxisToQuaternion(Kt,Zt),u.mulQuaternions(this.quaternion,Zt,Qt),this.quaternion=Qt,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return Kt[0]=e[0],Kt[1]=e[1],Kt[2]=e[2],Kt[3]=t*u.DEGTORAD,u.angleAxisToQuaternion(Kt,Zt),u.mulQuaternions(Zt,this.quaternion,Zt),this}rotateX(e){return this.rotate($t,e)}rotateY(e){return this.rotate(Jt,e)}rotateZ(e){return this.rotate(ei,e)}translate(e,t){return u.vec3ApplyQuaternion(this.quaternion,e,ti),u.mulVec3Scalar(ti,t,ii),u.addVec3(this.position,ii,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate($t,e)}translateY(e){return this.translate(Jt,e)}translateZ(e){return this.translate(ei,e)}_putDrawRenderers(){this._drawRenderer&&(this._drawRenderer.put(),this._drawRenderer=null),this._shadowRenderer&&(this._shadowRenderer.put(),this._shadowRenderer=null),this._emphasisFillRenderer&&(this._emphasisFillRenderer.put(),this._emphasisFillRenderer=null),this._emphasisEdgesRenderer&&(this._emphasisEdgesRenderer.put(),this._emphasisEdgesRenderer=null)}_putPickRenderers(){this._pickMeshRenderer&&(this._pickMeshRenderer.put(),this._pickMeshRenderer=null),this._pickTriangleRenderer&&(this._pickTriangleRenderer.put(),this._pickTriangleRenderer=null)}_putOcclusionRenderer(){this._occlusionRenderer&&(this._occlusionRenderer.put(),this._occlusionRenderer=null)}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set rtcCenter(e){e?(this._state.rtcCenter||(this._state.rtcCenter=u.vec3()),this._state.rtcCenter.set(e),this._state.rtcCenterHash=e.join(),this._setAABBDirty(),this.scene._aabbDirty=!0):this._state.rtcCenter&&(this._state.rtcCenter=null,this._state.rtcCenterHash=null,this._setAABBDirty(),this.scene._aabbDirty=!0)}get rtcCenter(){return this._state.rtcCenter}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._state.visible=e,this._isObject&&this.scene._objectVisibilityUpdated(this),this.glRedraw()}get visible(){return this._state.visible}set xrayed(e){e=!!e,this._state.xrayed!==e&&(this._state.xrayed=e,this._isObject&&this.scene._objectXRayedUpdated(this),this.glRedraw())}get xrayed(){return this._state.xrayed}set highlighted(e){(e=!!e)!==this._state.highlighted&&(this._state.highlighted=e,this._isObject&&this.scene._objectHighlightedUpdated(this),this.glRedraw())}get highlighted(){return this._state.highlighted}set selected(e){(e=!!e)!==this._state.selected&&(this._state.selected=e,this._isObject&&this.scene._objectSelectedUpdated(this),this.glRedraw())}get selected(){return this._state.selected}set edges(e){(e=!!e)!==this._state.edges&&(this._state.edges=e,this.glRedraw())}get edges(){return this._state.edges}set culled(e){this._state.culled=!!e,this.glRedraw()}get culled(){return this._state.culled}set clippable(e){e=!1!==e,this._state.clippable!==e&&(this._state.clippable=e,this.glRedraw())}get clippable(){return this._state.clippable}set collidable(e){(e=!1!==e)!==this._state.collidable&&(this._state.collidable=e,this._setAABBDirty(),this.scene._aabbDirty=!0)}get collidable(){return this._state.collidable}set pickable(e){e=!1!==e,this._state.pickable!==e&&(this._state.pickable=e)}get pickable(){return this._state.pickable}set castsShadow(e){(e=!1!==e)!==this._state.castsShadow&&(this._state.castsShadow=e,this.glRedraw())}get castsShadow(){return this._state.castsShadow}set receivesShadow(e){(e=!1!==e)!==this._state.receivesShadow&&(this._state.receivesShadow=e,this._state.hash=e?"/mod/rs;":"/mod;",this.fire("dirty",this))}get receivesShadow(){return this._state.receivesShadow}get saoEnabled(){return!1}set colorize(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);const i=!!e;this.scene._objectColorizeUpdated(this,i),this.glRedraw()}get colorize(){return this._state.colorize}set opacity(e){let t=this._state.colorize;t||(t=this._state.colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1);const i=null!=e;t[3]=i?e:1,this.scene._objectOpacityUpdated(this,i),this.glRedraw()}get opacity(){return this._state.colorize[3]}get transparent(){return 2===this._material.alphaMode||this._state.colorize[3]<1}set layer(e){e=e||0,(e=Math.round(e))!==this._state.layer&&(this._state.layer=e,this._renderer.needStateSort())}get layer(){return this._state.layer}get stationary(){return this._state.stationary}get billboard(){return this._state.billboard}set offset(e){this._state.offset.set(e||[0,0,0]),this._setAABBDirty(),this.glRedraw()}get offset(){return this._state.offset}get isDrawable(){return!0}get isStateSortable(){return!0}stateSortCompare(e,t){return e._state.layer-t._state.layer||e._drawRenderer.id-t._drawRenderer.id||e._material._state.id-t._material._state.id||e._geometry._state.id-t._geometry._state.id}rebuildRenderFlags(){this.renderFlags.reset(),this._getActiveSectionPlanes()?(this.renderFlags.numLayers=1,this.renderFlags.numVisibleLayers=1,this.renderFlags.visibleLayers[0]=0,this._updateRenderFlags()):this.renderFlags.culled=!0}_updateRenderFlags(){const e=this.renderFlags,t=this._state;if(t.xrayed){const t=this._xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}else if(this._material._state.alpha<1||t.colorize[3]<1?e.colorTransparent=!0:e.colorOpaque=!0,t.edges&&(this._edgeMaterial._state.alpha<1?e.edgesTransparent=!0:e.edgesOpaque=!0),t.selected){const t=this._selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}else if(t.highlighted){const t=this._highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}_getActiveSectionPlanes(){if(this._state.clippable){const e=this.scene._sectionPlanesState.sectionPlanes,t=e.length;if(t>0)for(let i=0;i<t;i++){const t=e[i],s=this.renderFlags;if(t.active)if(this._state.rtcCenter){const e=u.planeAABB3Intersect(t.dir,t.dist,this.aabb);if(-1===e)return!1;const r=0===e;s.sectionPlanesActivePerLayer[i]=r}else s.sectionPlanesActivePerLayer[i]=!0;else s.sectionPlanesActivePerLayer[i]=!1}}return!0}get xrayMaterial(){return this._xrayMaterial}get highlightMaterial(){return this._highlightMaterial}get selectedMaterial(){return this._selectedMaterial}get edgeMaterial(){return this._edgeMaterial}drawColorOpaque(e){(this._drawRenderer||(this._drawRenderer=Pt.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawColorTransparent(e){(this._drawRenderer||(this._drawRenderer=Pt.get(this)))&&this._drawRenderer.drawMesh(e,this)}drawSilhouetteXRayed(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Et.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,0)}drawSilhouetteHighlighted(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Et.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,1)}drawSilhouetteSelected(e){(this._emphasisFillRenderer||(this._emphasisFillRenderer=Et.get(this)))&&this._emphasisFillRenderer.drawMesh(e,this,2)}drawEdgesColorOpaque(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Lt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesColorTransparent(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Lt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,3)}drawEdgesXRayed(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Lt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,0)}drawEdgesHighlighted(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Lt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,1)}drawEdgesSelected(e){(this._emphasisEdgesRenderer||(this._emphasisEdgesRenderer=Lt.get(this)))&&this._emphasisEdgesRenderer.drawMesh(e,this,2)}drawOcclusion(e){(this._occlusionRenderer||(this._occlusionRenderer=Ut.get(this)))&&this._occlusionRenderer.drawMesh(e,this)}drawShadow(e){(this._shadowRenderer||(this._shadowRenderer=Ht.get(this)))&&this._shadowRenderer.drawMesh(e,this)}drawPickMesh(e){(this._pickMeshRenderer||(this._pickMeshRenderer=Ft.get(this)))&&this._pickMeshRenderer.drawMesh(e,this)}canPickTriangle(){return this._geometry.isReadableGeometry}drawPickTriangles(e){(this._pickTriangleRenderer||(this._pickTriangleRenderer=kt.get(this)))&&this._pickTriangleRenderer.drawMesh(e,this)}pickTriangleSurface(e,t,i){oi(this,e,t,i)}drawPickVertices(e){}delegatePickedEntity(){return this}destroy(){super.destroy(),this._putDrawRenderers(),this._putPickRenderers(),this._putOcclusionRenderer(),this.scene._renderer.putPickID(this._state.pickID),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this.glRedraw()}}const oi=function(){const e=u.vec3(),t=u.vec3(),i=u.vec3(),s=u.vec3(),r=u.vec3(),o=u.vec3(),a=u.vec4(),n=u.vec3(),l=u.vec3(),h=u.vec3(),c=u.vec3(),d=u.vec3(),p=u.vec3(),_=u.vec3(),f=u.vec3(),g=u.vec3(),m=u.vec4(),v=u.vec4(),b=u.vec4(),P=u.vec3(),y=u.vec3(),M=u.vec3(),x=u.vec3(),w=u.vec3(),E=u.vec3(),A=u.vec3(),C=u.vec3(),S=u.vec3(),D=u.vec3(),L=u.vec3();return function(B,T,R,F){var N=F.primIndex;if(null!=N&&N>-1){const V=B.geometry._state,j=B.scene,z=j.camera,U=j.canvas;if("triangles"===V.primitiveName){F.primitive="triangle";const j=N,G=V.indices,X=V.positions;let H,W,Y,q;if(G){var I=G[j+0],O=G[j+1],k=G[j+2];o[0]=I,o[1]=O,o[2]=k,F.indices=o,H=3*I,W=3*O,Y=3*k}else H=3*j,W=H+3,Y=W+3;if(i[0]=X[H+0],i[1]=X[H+1],i[2]=X[H+2],s[0]=X[W+0],s[1]=X[W+1],s[2]=X[W+2],r[0]=X[Y+0],r[1]=X[Y+1],r[2]=X[Y+2],V.compressGeometry){const e=V.positionsDecodeMatrix;e&&(Xe.decompressPosition(i,e,i),Xe.decompressPosition(s,e,s),Xe.decompressPosition(r,e,r))}F.canvasPos?(q=F.canvasPos,u.canvasPosToLocalRay(U.canvas,T,R,B.worldMatrix,q,e,t)):F.origin&&F.direction&&u.worldRayToLocalRay(B.worldMatrix,F.origin,F.direction,e,t),u.normalizeVec3(t),u.rayPlaneIntersect(e,t,i,s,r,a),F.localPos=a,F.position=a,m[0]=a[0],m[1]=a[1],m[2]=a[2],m[3]=1,u.transformVec4(B.worldMatrix,m,v),n[0]=v[0],n[1]=v[1],n[2]=v[2],F.worldPos=n,u.transformVec4(z.matrix,v,b),l[0]=b[0],l[1]=b[1],l[2]=b[2],F.viewPos=l,u.cartesianToBarycentric(a,i,s,r,h),F.bary=h;const K=V.normals;if(K){if(V.compressGeometry){const e=3*I,t=3*O,i=3*k;Xe.decompressNormal(K.subarray(e,e+2),c),Xe.decompressNormal(K.subarray(t,t+2),d),Xe.decompressNormal(K.subarray(i,i+2),p)}else c[0]=K[H],c[1]=K[H+1],c[2]=K[H+2],d[0]=K[W],d[1]=K[W+1],d[2]=K[W+2],p[0]=K[Y],p[1]=K[Y+1],p[2]=K[Y+2];const e=u.addVec3(u.addVec3(u.mulVec3Scalar(c,h[0],P),u.mulVec3Scalar(d,h[1],y),M),u.mulVec3Scalar(p,h[2],x),w);F.worldNormal=u.normalizeVec3(u.transformVec3(B.worldNormalMatrix,e,E))}const Z=V.uv;if(Z){if(_[0]=Z[2*I],_[1]=Z[2*I+1],f[0]=Z[2*O],f[1]=Z[2*O+1],g[0]=Z[2*k],g[1]=Z[2*k+1],V.compressGeometry){const e=V.uvDecodeMatrix;e&&(Xe.decompressUV(_,e,_),Xe.decompressUV(f,e,f),Xe.decompressUV(g,e,g))}F.uv=u.addVec3(u.addVec3(u.mulVec2Scalar(_,h[0],A),u.mulVec2Scalar(f,h[1],C),S),u.mulVec2Scalar(g,h[2],D),L)}}}}}();function ai(e={}){let t=e.radiusTop||1;t<0&&(console.error("negative radiusTop not allowed - will invert"),t*=-1);let i=e.radiusBottom||1;i<0&&(console.error("negative radiusBottom not allowed - will invert"),i*=-1);let s=e.height||1;s<0&&(console.error("negative height not allowed - will invert"),s*=-1);let r=e.radialSegments||32;r<0&&(console.error("negative radialSegments not allowed - will invert"),r*=-1),r<3&&(r=3);let o=e.heightSegments||1;o<0&&(console.error("negative heightSegments not allowed - will invert"),o*=-1),o<1&&(o=1);const a=!!e.openEnded;let n=e.center;const l=n?n[0]:0,h=n?n[1]:0,c=n?n[2]:0,u=s/2,d=s/o,p=2*Math.PI/r,_=1/r,g=(t-i)/o,m=[],v=[],b=[],P=[];let y,M,x,w,E,A,C,S,D,L,B;const T=(90-180*Math.atan(s/(i-t))/Math.PI)/90;for(y=0;y<=o;y++)for(E=t-y*g,A=u-y*d,M=0;M<=r;M++)x=Math.sin(M*p),w=Math.cos(M*p),v.push(E*x),v.push(T),v.push(E*w),b.push(M*_),b.push(1*y/o),m.push(E*x+l),m.push(A+h),m.push(E*w+c);for(y=0;y<o;y++)for(M=0;M<=r;M++)C=y*(r+1)+M,S=C+r,P.push(C),P.push(S),P.push(S+1),P.push(C),P.push(S+1),P.push(C+1);if(!a&&t>0){for(D=m.length/3,v.push(0),v.push(1),v.push(0),b.push(.5),b.push(.5),m.push(0+l),m.push(u+h),m.push(0+c),M=0;M<=r;M++)x=Math.sin(M*p),w=Math.cos(M*p),L=.5*Math.sin(M*p)+.5,B=.5*Math.cos(M*p)+.5,v.push(t*x),v.push(1),v.push(t*w),b.push(L),b.push(B),m.push(t*x+l),m.push(u+h),m.push(t*w+c);for(M=0;M<r;M++)n=D,C=D+1+M,P.push(C),P.push(C+1),P.push(n)}if(!a&&i>0){for(D=m.length/3,v.push(0),v.push(-1),v.push(0),b.push(.5),b.push(.5),m.push(0+l),m.push(0-u+h),m.push(0+c),M=0;M<=r;M++)x=Math.sin(M*p),w=Math.cos(M*p),L=.5*Math.sin(M*p)+.5,B=.5*Math.cos(M*p)+.5,v.push(i*x),v.push(-1),v.push(i*w),b.push(L),b.push(B),m.push(i*x+l),m.push(0-u+h),m.push(i*w+c);for(M=0;M<r;M++)n=D,C=D+1+M,P.push(n),P.push(C+1),P.push(C)}return f.apply(e,{positions:m,normals:v,uv:b,indices:P})}function ni(e={}){const t=e.lod||1,i=e.center?e.center[0]:0,s=e.center?e.center[1]:0,r=e.center?e.center[2]:0;let o=e.radius||1;o<0&&(console.error("negative radius not allowed - will invert"),o*=-1);let a=e.heightSegments||18;a<0&&(console.error("negative heightSegments not allowed - will invert"),a*=-1),a=Math.floor(t*a),a<18&&(a=18);let n=e.widthSegments||18;n<0&&(console.error("negative widthSegments not allowed - will invert"),n*=-1),n=Math.floor(t*n),n<18&&(n=18);const l=[],h=[],c=[],u=[];let d,p,_,g,m,v,b,P,y,M,x,w,E,A,C;for(d=0;d<=a;d++)for(_=d*Math.PI/a,g=Math.sin(_),m=Math.cos(_),p=0;p<=n;p++)v=2*p*Math.PI/n,b=Math.sin(v),P=Math.cos(v),y=P*g,M=m,x=b*g,w=1-p/n,E=d/a,h.push(y),h.push(M),h.push(x),c.push(w),c.push(E),l.push(i+o*y),l.push(s+o*M),l.push(r+o*x);for(d=0;d<a;d++)for(p=0;p<n;p++)A=d*(n+1)+p,C=A+n+1,u.push(A+1),u.push(C+1),u.push(C),u.push(A+1),u.push(C),u.push(A);return f.apply(e,{positions:l,normals:h,uv:c,indices:u})}class li extends A{get type(){return"SectionPlane"}constructor(e,t={}){super(e,t),this._state=new me({active:!0,pos:u.vec3(),dir:u.vec3(),dist:0}),this.active=t.active,this.pos=t.pos,this.dir=t.dir,this.scene._sectionPlaneCreated(this)}set active(e){this._state.active=!1!==e,this.glRedraw(),this.fire("active",this._state.active)}get active(){return this._state.active}set pos(e){this._state.pos.set(e||[0,0,0]),this._state.dist=-u.dotVec3(this._state.pos,this._state.dir),this.fire("pos",this._state.pos)}get pos(){return this._state.pos}set dir(e){this._state.dir.set(e||[0,0,-1]),this._state.dist=-u.dotVec3(this._state.pos,this._state.dir),this.glRedraw(),this.fire("dir",this._state.dir)}get dir(){return this._state.dir}get dist(){return this._state.dist}flipDir(){const e=this._state.dir;e[0]*=-1,e[1]*=-1,e[2]*=-1,this._state.dist=-u.dotVec3(this._state.pos,this._state.dir),this.fire("dir",this._state.dir),this.glRedraw()}destroy(){this._state.destroy(),this.scene._sectionPlaneDestroyed(this),super.destroy()}}const hi=u.vec3();class ci extends a{constructor(e,t={}){super("BCFViewpoints",e,t),this.originatingSystem=t.originatingSystem||"xeokit.io",this.authoringTool=t.authoringTool||"xeokit.io"}getViewpoint(e={}){const t=this.viewer.scene,i=t.camera,s=t.realWorldOffset,r=!0===e.reverseClippingPlanes;let o={},a=u.normalizeVec3(u.subVec3(i.look,i.eye,u.vec3())),n=i.eye,l=i.up;i.yUp&&(a=pi(a),n=pi(n),l=pi(l));const h=ui(u.addVec3(n,s));"ortho"===i.projection?o.orthogonal_camera={camera_view_point:h,camera_direction:ui(a),camera_up_vector:ui(l),view_to_world_scale:i.ortho.scale}:o.perspective_camera={camera_view_point:h,camera_direction:ui(a),camera_up_vector:ui(l),field_of_view:i.perspective.fov};const c=t.sectionPlanes;for(let e in c)if(c.hasOwnProperty(e)){let t,a=c[e],n=a.pos;t=r?u.negateVec3(a.dir,u.vec3()):a.dir,i.yUp&&(n=pi(n),t=pi(t)),u.addVec3(n,s),n=ui(n),t=ui(t),o.clipping_planes||(o.clipping_planes=[]),o.clipping_planes.push({location:n,direction:t})}o.components={visibility:{view_setup_hints:{spaces_visible:!!e.spacesVisible,space_boundaries_visible:!!e.spaceBoundariesVisible,openings_visible:!!e.openingsVisible}}};const d=new Set(t.opacityObjectIds),p=new Set(t.xrayedObjectIds),_=new Set(t.colorizedObjectIds),f=Object.values(t.objects).filter((e=>d.has(e.id)||_.has(e.id)||p.has(e.id))).reduce(((e,i)=>{let s,r=function(e){let t="";return t+=Math.round(255*e[0]).toString(16).padStart(2,"0"),t+=Math.round(255*e[1]).toString(16).padStart(2,"0"),t+=Math.round(255*e[2]).toString(16).padStart(2,"0"),t}(i.colorize);i.xrayed?(s=0===t.xrayMaterial.fillAlpha&&0!==t.xrayMaterial.edgeAlpha?.1:t.xrayMaterial.fillAlpha,s=Math.round(255*s).toString(16).padStart(2,"0"),r=s+r):d.has(i.id)&&(s=Math.round(255*i.opacity).toString(16).padStart(2,"0"),r=s+r),e[r]||(e[r]=[]);const o=i.id,a=i.originalSystemId,n={ifc_guid:a,originating_system:this.originatingSystem};return a!==o&&(n.authoring_tool_id=o),e[r].push(n),e}),{}),g=Object.entries(f).map((([e,t])=>({color:e,components:t})));o.components.coloring=g;const m=t.objectIds,v=t.visibleObjects,b=t.visibleObjectIds,P=m.filter((e=>!v[e])),y=t.selectedObjectIds;return e.defaultInvisible||b.length<P.length?(o.components.visibility.exceptions=this._createBCFComponents(b),o.components.visibility.default_visibility=!1):(o.components.visibility.exceptions=this._createBCFComponents(P),o.components.visibility.default_visibility=!0),o.components.selection=this._createBCFComponents(y),!1!==e.snapshot&&(o.snapshot={snapshot_type:"png",snapshot_data:this.viewer.getSnapshot({format:"png"})}),o}_createBCFComponents(e){const t=this.viewer.scene,i=[];for(let s=0,r=e.length;s<r;s++){const r=e[s],o=t.objects[r];if(o){const e={ifc_guid:o.originalSystemId,originating_system:this.originatingSystem};o.originalSystemId!==r&&(e.authoring_tool_id=r),i.push(e)}}return i}setViewpoint(e,t={}){if(!e)return;const i=this.viewer,s=i.scene,r=s.camera,o=!1!==t.rayCast,a=!1!==t.immediate,n=!1!==t.reset,l=s.realWorldOffset,h=!0===t.reverseClippingPlanes;if(s.clearSectionPlanes(),e.clipping_planes&&e.clipping_planes.forEach((function(e){let t=di(e.location,hi),i=di(e.direction,hi);h&&u.negateVec3(i),u.subVec3(t,l),r.yUp&&(t=_i(t),i=_i(i)),new li(s,{pos:t,dir:i})})),n&&(s.setObjectsXRayed(s.xrayedObjectIds,!1),s.setObjectsHighlighted(s.highlightedObjectIds,!1),s.setObjectsSelected(s.selectedObjectIds,!1)),e.components){if(e.components.visibility){e.components.visibility.default_visibility?(s.setObjectsVisible(s.objectIds,!0),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!1))))):(s.setObjectsVisible(s.objectIds,!1),e.components.visibility.exceptions&&e.components.visibility.exceptions.forEach((e=>this._withBCFComponent(t,e,(e=>e.visible=!0)))));const r=e.components.visibility.view_setup_hints;r&&(!1===r.spaces_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcSpace"),!1),!1===r.openings_visible&&s.setObjectsVisible(i.metaScene.getObjectIDsByType("IfcOpening"),!1),r.space_boundaries_visible)}e.components.selection&&(s.setObjectsSelected(s.selectedObjectIds,!1),e.components.selection.forEach((e=>this._withBCFComponent(t,e,(e=>e.selected=!0))))),e.components.coloring&&e.components.coloring.forEach((e=>{let i=e.color,s=0,r=!1;8===i.length&&(s=parseInt(i.substring(0,2),16)/256,s<=1&&s>=.95&&(s=1),i=i.substring(2),r=!0);const o=[parseInt(i.substring(0,2),16)/256,parseInt(i.substring(2,4),16)/256,parseInt(i.substring(4,6),16)/256];e.components.map((e=>this._withBCFComponent(t,e,(e=>{e.colorize=o,r&&(e.opacity=s)}))))}))}if(e.perspective_camera||e.orthogonal_camera){let n,h,c,d;if(e.perspective_camera?(n=di(e.perspective_camera.camera_view_point,hi),h=di(e.perspective_camera.camera_direction,hi),c=di(e.perspective_camera.camera_up_vector,hi),r.perspective.fov=e.perspective_camera.field_of_view,d="perspective"):(n=di(e.orthogonal_camera.camera_view_point,hi),h=di(e.orthogonal_camera.camera_direction,hi),c=di(e.orthogonal_camera.camera_up_vector,hi),r.ortho.scale=e.orthogonal_camera.view_to_world_scale,d="ortho"),u.subVec3(n,l),r.yUp&&(n=_i(n),h=_i(h),c=_i(c)),o){const e=s.pick({pickSurface:!0,origin:n,direction:h});h=e?e.worldPos:u.addVec3(n,h,hi)}else h=u.addVec3(n,h,hi);a?(r.eye=n,r.look=h,r.up=c,r.projection=d):i.cameraFlight.flyTo({eye:n,look:h,up:c,duration:t.duration,projection:d})}}_withBCFComponent(e,t,i){const s=this.viewer,r=s.scene;if(t.authoring_tool_id&&t.originating_system===this.originatingSystem){const o=t.authoring_tool_id,a=r.objects[o];if(a)return void i(a);if(e.updateCompositeObjects&&s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i)}if(t.ifc_guid){const o=t.ifc_guid,a=r.objects[o];if(a)return void i(a);if(e.updateCompositeObjects&&s.metaScene.metaObjects[o])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(o),i);Object.keys(r.models).forEach((t=>{const a=u.globalizeObjectId(t,o),n=r.objects[a];if(n)i(n);else if(e.updateCompositeObjects&&s.metaScene.metaObjects[a])return void r.withObjects(s.metaScene.getObjectIDsInSubtree(a),i)}))}}destroy(){super.destroy()}}function ui(e){return{x:e[0],y:e[1],z:e[2]}}function di(e,t){return(t=new Float64Array(3))[0]=e.x,t[1]=e.y,t[2]=e.z,t}function pi(e){return new Float64Array([e[0],-e[2],e[1]])}function _i(e){return new Float64Array([e[0],e[2],-e[1]])}u.vec3();class fi extends a{constructor(e,t={}){super("FastNav",e),this._pbrEnabled=void 0!==t.pbrEnabled&&null!==t.pbrEnabled?t.pbrEnabled:e.scene.pbrEnabled,this._saoEnabled=void 0!==t.saoEnabled&&null!==t.saoEnabled?t.saoEnabled:e.scene.sao.enabled,this._edgesEnabled=void 0!==t.edgesEnabled&&null!==t.edgesEnabled?t.edgesEnabled:e.scene.edgeMaterial.edges,this._pInterval=null,this._fadeMillisecs=500;let i=600,s=i,r=!1;this._onCanvasBoundary=e.scene.canvas.on("boundary",(()=>{s=i,r||(this._cancelFade(),e.scene.pbrEnabled=!1,e.scene.sao.enabled=!1,e.scene.edgeMaterial.edges=!1,r=!0)})),this._onCameraMatrix=e.scene.camera.on("matrix",(()=>{s=i,r||(this._cancelFade(),e.scene.pbrEnabled=!1,e.scene.sao.enabled=!1,e.scene.edgeMaterial.edges=!1,r=!0)})),this._onSceneTick=e.scene.on("tick",(t=>{r&&(s-=t.deltaTime,s<=0&&r&&(this._startFade(),this._pInterval2=setTimeout((()=>{e.scene.pbrEnabled=this._pbrEnabled,e.scene.sao.enabled=this._saoEnabled,e.scene.edgeMaterial.edges=this._edgesEnabled}),100),r=!1))}));let o=!1;this._onSceneMouseDown=e.scene.input.on("mousedown",(()=>{s=i,r||(this._cancelFade(),e.scene.pbrEnabled=!1,e.scene.sao.enabled=!1,e.scene.edgeMaterial.edges=!1,r=!0),o=!0})),this._onSceneMouseUp=e.scene.input.on("mouseup",(()=>{o=!1})),this._onSceneMouseMove=e.scene.input.on("mousemove",(()=>{o&&(s=i,r||(this._cancelFade(),e.scene.pbrEnabled=!1,e.scene.sao.enabled=!1,e.scene.edgeMaterial.edges=!1,r=!0))}))}_startFade(){this._img||this._initFade();const e=1/(this._fadeMillisecs/50);this._pInterval&&(clearInterval(this._pInterval),this._pInterval=null);const t=this.viewer,i=t.scene.canvas.canvas,s=gi(i),r=(parseInt(i.style["z-index"])||0)+1;this._img.style.position="fixed",this._img.style.margin="0px",this._img.style["z-index"]=r,this._img.style.background=i.style.background,this._img.style.left=s.left+"px",this._img.style.top=s.top+"px",this._img.style.width=i.width+"px",this._img.style.height=i.height+"px",this._img.width=i.width,this._img.height=i.height,this._img.src="",this._img.src=t.getSnapshot({format:"png",includeGizmos:!0}),this._img.style.visibility="visible",this._img.style.opacity=1;let o=1;this._pInterval=setInterval((()=>{if(o-=e,o>0){this._img.style.opacity=o;const e=gi(i);this._img.style.left=e.left+"px",this._img.style.top=e.top+"px",this._img.style.width=i.width+"px",this._img.style.height=i.height+"px",this._img.style.opacity=o,this._img.width=i.width,this._img.height=i.height}else this._img.style.opacity=0,this._img.style.visibility="hidden",clearInterval(this._pInterval),this._pInterval=null}),50)}_initFade(){this._img=document.createElement("img");const e=this.viewer.scene.canvas.canvas,t=gi(e);parseInt(e.style["z-index"]),this._img.style.position="absolute",this._img.style.visibility="hidden",this._img.style["pointer-events"]="none",this._img.style["z-index"]=5,this._img.style.left=t.left+"px",this._img.style.top=t.top+"px",this._img.style.width=e.width+"px",this._img.style.height=e.height+"px",this._img.style.opacity=1,this._img.width=e.width,this._img.height=e.height,this._img.left=t.left,this._img.top=t.top,e.parentNode.insertBefore(this._img,e.nextSibling)}_cancelFade(){this._img&&(this._pInterval&&(clearInterval(this._pInterval),this._pInterval=null),this._pInterval2&&(clearInterval(this._pInterval2),this._pInterval2=null),this._img.style.opacity=0,this._img.style.visibility="hidden")}set pbrEnabled(e){this._pbrEnabled=e}get pbrEnabled(){return this._pbrEnabled}set saoEnabled(e){this._saoEnabled=e}get saoEnabled(){return this._saoEnabled}set edgesEnabled(e){this._edgesEnabled=e}get edgesEnabled(){return this._edgesEnabled}send(e,t){switch(e){case"clear":this._cancelFade()}}destroy(){this._cancelFade(),this.viewer.scene.camera.off(this._onCameraMatrix),this.viewer.scene.canvas.off(this._onCanvasBoundary),this.viewer.scene.input.off(this._onSceneMouseDown),this.viewer.scene.input.off(this._onSceneMouseUp),this.viewer.scene.input.off(this._onSceneMouseMove),this.viewer.scene.off(this._onSceneTick),super.destroy(),this._img&&(this._img.parentNode.removeChild(this._img),this._img=null)}}function gi(e){let t=0,i=0;do{t+=e.offsetTop||0,i+=e.offsetLeft||0,e=e.offsetParent}while(e);return{top:t,left:i}}class mi{constructor(e,t,i,s,r=null,o=0){this.model=e,this.object=null,this.parent=null,this.id=t,this.pickId=this.model.scene._renderer.getPickID(this),this.aabb=u.AABB3(),this._layer=r,this._portionId=o,this._color=[i[0],i[1],i[2],s],this._colorize=[i[0],i[1],i[2],s],this._colorizing=!1,this._transparent=s<255,this.numTriangles=0,this.rtcCenter=null}_finalize(e){this._layer.initFlags(this._portionId,e,this._transparent)}_setVisible(e){this._layer.setVisible(this._portionId,e,this._transparent)}_setColor(e){this._color[0]=e[0],this._color[1]=e[1],this._color[2]=e[2],this._colorizing||this._layer.setColor(this._portionId,this._color,!1)}_setColorize(e){e?(this._colorize[0]=e[0],this._colorize[1]=e[1],this._colorize[2]=e[2],this._layer.setColor(this._portionId,this._colorize,!1),this._colorizing=!0):(this._layer.setColor(this._portionId,this._color,!1),this._colorizing=!1)}_setOpacity(e,t){const i=e<255,s=this._transparent!==i;this._color[3]=e,this._colorize[3]=e,this._transparent=i,this._colorizing?this._layer.setColor(this._portionId,this._colorize):this._layer.setColor(this._portionId,this._color),s&&this._layer.setTransparent(this._portionId,t,i)}_setOffset(e){this._layer.setOffset(this._portionId,e)}_setHighlighted(e){this._layer.setHighlighted(this._portionId,e,this._transparent)}_setXRayed(e){this._layer.setXRayed(this._portionId,e,this._transparent)}_setSelected(e){this._layer.setSelected(this._portionId,e,this._transparent)}_setEdges(e){this._layer.setEdges(this._portionId,e,this._transparent)}_setClippable(e){this._layer.setClippable(this._portionId,e,this._transparent)}_setCollidable(e){this._layer.setCollidable(this._portionId,e)}_setPickable(e){this._layer.setPickable(this._portionId,e,this._transparent)}_setCulled(e){this._layer.setCulled(this._portionId,e,this._transparent)}canPickTriangle(){return!1}drawPickTriangles(e,t){}pickTriangleSurface(e){}canPickWorldPos(){return!0}drawPickDepths(e){this.model.drawPickDepths(e)}drawPickNormals(e){this.model.drawPickNormals(e)}delegatePickedEntity(){return this.parent}_destroy(){this.model.scene._renderer.putPickID(this.pickId)}}const vi=new class{constructor(){this._uint8Arrays={},this._float32Arrays={}}_clear(){this._uint8Arrays={},this._float32Arrays={}}getUInt8Array(e){let t=this._uint8Arrays[e];return t||(t=new Uint8Array(e),this._uint8Arrays[e]=t),t}getFloat32Array(e){let t=this._float32Arrays[e];return t||(t=new Float32Array(e),this._float32Arrays[e]=t),t}};let bi=0;const Pi=u.vec4(),yi=u.vec3();class Mi{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,a=s.canvas.gl,n=t._state,l=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,l?I(r.viewMatrix,l):r.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,o.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,o.worldNormalMatrix);const h=s._sectionPlanesState.sectionPlanes.length;if(h>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*h,r=o.renderFlags;for(let t=0;t<h;t++){const s=this._uSectionPlanes[t],o=r.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,o?1:0),o){const i=e[t];if(l){const e=O(i.dist,i.dir,l,yi);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(n.normalsBuf),this._aColor&&this._aColor.bindArrayBuffer(n.colorsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),n.indicesBuf.bind(),a.drawElements(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e<t;e++)switch(o=r[e],o.type){case"dir":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=s.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=s.getLocation("lightDir"+e),this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e)}this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t._lightsState.lights,o=t.camera.project;s.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,o.matrix),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(let e=0,t=r.length;e<t;e++){const t=r[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const s=t.sao;if(s.possible){const t=i.drawingBufferWidth,r=i.drawingBufferHeight;Pi[0]=t,Pi[1]=r,Pi[2]=s.blendCutoff,Pi[3]=s.blendFactor,i.uniform4fv(this._uSAOParams,Pi),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,0)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0;let r;const o=[];o.push("// Triangles batching draw vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("uniform int renderPass;"),o.push("attribute vec3 position;"),o.push("attribute vec3 normal;"),o.push("attribute vec4 color;"),o.push("attribute vec4 flags;"),o.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&o.push("attribute vec3 offset;"),o.push("uniform mat4 worldMatrix;"),o.push("uniform mat4 worldNormalMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform mat4 viewNormalMatrix;"),o.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("varying float vFragDepth;")),o.push("uniform vec4 lightAmbient;");for(let e=0,t=i.lights.length;e<t;e++)r=i.lights[e],"ambient"!==r.type&&(o.push("uniform vec4 lightColor"+e+";"),"dir"===r.type&&o.push("uniform vec3 lightDir"+e+";"),"point"===r.type&&o.push("uniform vec3 lightPos"+e+";"),"spot"===r.type&&(o.push("uniform vec3 lightPos"+e+";"),o.push("uniform vec3 lightDir"+e+";")));o.push("vec3 octDecode(vec2 oct) {"),o.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push("    if (v.z < 0.0) {"),o.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push("    }"),o.push("    return normalize(v);"),o.push("}"),s&&(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;")),o.push("varying vec4 vColor;"),o.push("void main(void) {"),o.push("if (int(flags.x) != renderPass) {"),o.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition  = viewMatrix * worldPosition; "),o.push("vec4 worldNormal =  worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),o.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),o.push("float lambertian = 1.0;");for(let e=0,t=i.lights.length;e<t;e++)if(r=i.lights[e],"ambient"!==r.type){if("dir"===r.type)"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===r.type)"view"===r.space?o.push("viewLightDir = -normalize(lightPos"+e+" - viewPosition.xyz);"):o.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==r.type)continue;"view"===r.space?o.push("viewLightDir = normalize(lightDir"+e+");"):o.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}o.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),o.push("reflectedColor += lambertian * (lightColor"+e+".rgb * lightColor"+e+".a);")}return o.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),o.push("vColor =  vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?o.push("vFragDepth = 1.0 + clipPos.w;"):(o.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),o.push("clipPos.z *= clipPos.w;"))),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags2 = flags2;")),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Triangles batching draw fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4      uSAOParams;"),s.push("const float       packUpscale = 256. / 255.;"),s.push("const float       unpackDownScale = 255. / 256.;"),s.push("const vec3        packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );"),s.push("const vec4        unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push("    return dot( v, unPackFactors );"),s.push("}")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { "),s.push("      discard;"),s.push("  }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push("   float viewportWidth     = uSAOParams[0];"),s.push("   float viewportHeight    = uSAOParams[1];"),s.push("   float blendCutoff       = uSAOParams[2];"),s.push("   float blendFactor       = uSAOParams[3];"),s.push("   vec2 uv                 = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push("   float ambient           = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture2D(uOcclusionTexture, uv))) * blendFactor;"),s.push("   gl_FragColor            = vec4(vColor.rgb * ambient, 1.0);")):s.push("   gl_FragColor            = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xi=new Float32Array([1,1,1]),wi=u.vec3();class Ei{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),5===i){const e=r.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(3===i){const e=r.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(4===i){const e=r.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else a.uniform4fv(this._uColor,xi);const h=l?I(o.viewMatrix,l):o.viewMatrix;a.uniformMatrix4fv(this._uViewMatrix,!1,h),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,wi);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),n.indicesBuf.bind(),a.drawElements(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uColor=i.getLocation("color"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Triangles batching silhouette vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("if (int(flags.y) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Triangles batching silhouette fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(o.push("uniform float logDepthBufFC;"),o.push("varying float vFragDepth;")),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("uniform vec4 color;"),o.push("void main(void) {"),r){for(o.push("  bool clippable = (float(vFlags2.x) > 0.0);"),o.push("  if (clippable) {"),o.push("  float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push("   dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("  if (dist > 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("gl_FragColor = color;"),o.push("}"),o}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ai=u.vec3(),Ci=new Float32Array([0,0,0,1]);class Si{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),10===i){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(8===i){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(9===i){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else a.uniform4fv(this._uColor,Ci);a.uniformMatrix4fv(this._uViewMatrix,!1,l?I(o.viewMatrix,l):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const h=r._sectionPlanesState.sectionPlanes.length;if(h>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*h,o=s.renderFlags;for(let t=0;t<h;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Ai);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),n.edgeIndicesBuf.bind(),a.drawElements(a.LINES,n.edgeIndicesBuf.numItems,n.edgeIndicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uColor=i.getLocation("color"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry edges drawing vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vColor;"),i.push("void main(void) {"),i.push("if (int(flags.z) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("  vWorldPosition = worldPosition;"),i.push("  vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Di=u.vec3();class Li{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,l?I(o.viewMatrix,l):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const h=r._sectionPlanesState.sectionPlanes.length;if(h>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*h,o=s.renderFlags;for(let t=0;t<h;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Di);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aColor.bindArrayBuffer(n.colorsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),n.edgeIndicesBuf.bind(),a.drawElements(a.LINES,n.edgeIndicesBuf.numItems,n.edgeIndicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aColor=i.getAttribute("color"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry edges drawing vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec4 color;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vColor;"),i.push("void main(void) {"),i.push("if (int(flags.z) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("  vWorldPosition = worldPosition;"),i.push("  vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Bi=u.vec3();class Ti{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const h=e.pickViewMatrix||o.viewMatrix,c=l?I(h,l):h;if(a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),a.uniformMatrix4fv(this._uViewMatrix,!1,c),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const u=r._sectionPlanesState.sectionPlanes.length;if(u>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*u,o=s.renderFlags;for(let t=0;t<u;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Bi);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),this._aPickColor&&this._aPickColor.bindArrayBuffer(n.pickColorsBuf),n.indicesBuf.bind(),a.drawElements(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aPickColor=i.getAttribute("pickColor"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry picking vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 pickColor;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vPickColor;"),i.push("void main(void) {"),i.push("if (int(flags.w) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("  } else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),i.push("      vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("  }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry picking fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec4 vPickColor;"),s.push("void main(void) {"),i){for(s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;"),r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("   gl_FragColor = vPickColor; "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ri=u.vec3();class Fi{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniform1i(this._uPickInvisible,e.pickInvisible);const h=e.pickViewMatrix||o.viewMatrix,c=l?I(h,l):h;if(a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uViewMatrix,!1,c),a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),a.uniform1f(this._uPickZNear,e.pickZNear),a.uniform1f(this._uPickZFar,e.pickZFar),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const u=r._sectionPlanesState.sectionPlanes.length;if(u>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*u,o=s.renderFlags;for(let t=0;t<u;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Ri);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),n.indicesBuf.bind(),a.drawElements(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Triangles batching pick depth vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("if (int(flags.w) != renderPass) {"),i.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("  } else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("  }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Triangles batching pick depth fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push("  const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push("  const vec4 bitMask  = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push("  vec4 res = fract(depth * bitShift);"),s.push("  res -= res.xxyz * bitMask;"),s.push("  return res;"),s.push("}"),s.push("void main(void) {"),i){for(s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;"),r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push("    gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ni=u.vec3();class Ii{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniform1i(this._uPickInvisible,e.pickInvisible),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const h=e.pickViewMatrix||o.viewMatrix,c=l?I(h,l):h;if(a.uniformMatrix4fv(this._uViewMatrix,!1,c),a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const u=r._sectionPlanesState.sectionPlanes.length;if(u>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*u,o=s.renderFlags;for(let t=0;t<u;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Ni);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(n.normalsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),n.indicesBuf.bind(),a.drawElements(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Triangles batching pick normals vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),i.push("vec3 octDecode(vec2 oct) {"),i.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push("    if (v.z < 0.0) {"),i.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push("    }"),i.push("    return normalize(v);"),i.push("}"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("if (int(flags.w) != renderPass) {"),i.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("  } else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),i.push("      vec3 worldNormal =  octDecode(normal.xy); "),i.push("      vWorldNormal = worldNormal;"),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("  }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Triangles batching pick normals fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec3 vWorldNormal;"),s.push("void main(void) {"),i){for(s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;"),r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    gl_FragColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Oi=u.vec3();class ki{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.canvas.gl,a=t._state,n=r.camera,l=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uViewMatrix,!1,l?I(n.viewMatrix,l):n.viewMatrix),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const h=r._sectionPlanesState.sectionPlanes.length;if(h>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*h,a=s.renderFlags;for(let t=0;t<h;t++){const s=this._uSectionPlanes[t],r=a.sectionPlanesActivePerLayer[i+t];if(o.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Oi);o.uniform3fv(s.pos,e)}else o.uniform3fv(s.pos,i.pos);o.uniform3fv(s.dir,i.dir)}}}o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(a.offsetsBuf),this._aColor&&this._aColor.bindArrayBuffer(a.colorsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),a.indicesBuf.bind(),o.drawElements(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Triangles batching occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("  } else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("  }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Triangles batching occlusion fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("      if (sectionPlaneActive"+e+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("   gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Vi=u.vec3();class ji{constructor(e){this._scene=e,this._allocate(),this._hash=this._getHash()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uViewMatrix,!1,l?I(o.viewMatrix,l):o.viewMatrix);const h=r._sectionPlanesState.sectionPlanes.length;if(h>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*h,o=s.renderFlags;for(let t=0;t<h;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Vi);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),n.indicesBuf.bind(),a.drawElements(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Triangles batching depth vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("  } else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("  }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Triangles batching depth fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("precision highp float;"),s.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("const float   packUpScale = 256. / 255.;"),s.push("const float   unpackDownscale = 255. / 256.;"),s.push("const vec3    packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );"),s.push("const vec4    unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),s.push("const float   shiftRight8 = 1.0 / 256.;"),s.push("vec4 packDepthToRGBA( const in float v ) {"),s.push("    vec4 r = vec4( fract( v * packFactors ), v );"),s.push("    r.yzw -= r.xyz * shiftRight8;"),s.push("    return r * packUpScale;"),s.push("}"),s.push("varying vec2 vHighPrecisionZW;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture?s.push("    gl_FragColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "):s.push("    gl_FragColor = packDepthToRGBA(fragCoordZ); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null,d.memory.programs--}}const zi=u.vec3();class Ui{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(t)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,l?I(o.viewMatrix,l):o.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const h=r._sectionPlanesState.sectionPlanes.length;if(h>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*h,o=s.renderFlags;for(let t=0;t<h;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,zi);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aNormal.bindArrayBuffer(n.normalsBuf),this._aColor.bindArrayBuffer(n.colorsBuf),this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),n.indicesBuf.bind(),a.drawElements(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uWorldNormalMatrix=i.getLocation("worldNormalMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uViewNormalMatrix=i.getLocation("viewNormalMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aNormal=i.getAttribute("normal"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2&&(this._aFlags2=i.getAttribute("flags2")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),i.push("vec3 octDecode(vec2 oct) {"),i.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push("    if (v.z < 0.0) {"),i.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push("    }"),i.push("    return normalize(v);"),i.push("}"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("  } else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("      vec4 viewPosition   = viewMatrix * worldPosition; "),i.push("      vec4 worldNormal    = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push("      vec3 viewNormal     = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("      vWorldPosition  = worldPosition;"),i.push("      vFlags2         = flags2;")),i.push("      vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("  }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push("    return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Gi=u.vec3();class Xi{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=this._scene,s=i.canvas.gl,r=t._state;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),s.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),i.logarithmicDepthBufferEnabled&&s.uniform1f(this._uZFar,i.camera.project.far),this._aPosition.bindArrayBuffer(r.positionsBuf),this._aColor&&this._aColor.bindArrayBuffer(r.colorsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(r.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(r.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(r.offsetsBuf),r.indicesBuf.bind();const o=i._sectionPlanesState.sectionPlanes.length;if(o>0){const e=i._sectionPlanesState.sectionPlanes,r=t.layerIndex*o,a=model.renderFlags,n=t._state.rtcCenter;for(let t=0;t<o;t++){const i=this._uSectionPlanes[t],o=a.sectionPlanesActivePerLayer[r+t];if(s.uniform1i(i.active,o?1:0),o){const r=e[t];if(n){const e=O(r.dist,r.dir,n,Gi);s.uniform3fv(i.pos,e)}else s.uniform3fv(i.pos,r.pos);s.uniform3fv(i.dir,r.dir)}}}s.drawElements(s.TRIANGLES,r.indicesBuf.numItems,r.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),e.logarithmicDepthBufferEnabled&&(this._uZFar=s.getLocation("zFar")),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2")}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),t.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastLightId=null}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Batched geometry shadow vertex shader"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("  bool visible        = (float(flags.x) > 0.0);"),i.push("  bool transparent    = ((float(color.a) / 255.0) < 1.0);"),i.push("  if (!visible || transparent) {"),i.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("  } else {"),i.push("      vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("      vec4 viewPosition  = shadowViewMatrix * worldPosition; "),t&&(i.push("      vWorldPosition = worldPosition;"),i.push("      vFlags2 = flags2;")),i.push("      vViewPosition = viewPosition;"),i.push("      gl_Position = shadowProjMatrix * viewPosition;"),i.push("  }"),i.push("}"),i}_buildFragmentShader(){const e=this._scene._sectionPlanesState,t=e.sectionPlanes.length>0,i=[];if(i.push("// Batched geometry shadow fragment shader"),i.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),i.push("precision highp float;"),i.push("precision highp int;"),i.push("#else"),i.push("precision mediump float;"),i.push("precision mediump int;"),i.push("#endif"),t){i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;");for(let t=0;t<e.sectionPlanes.length;t++)i.push("uniform bool sectionPlaneActive"+t+";"),i.push("uniform vec3 sectionPlanePos"+t+";"),i.push("uniform vec3 sectionPlaneDir"+t+";")}if(i.push("varying vec4 vViewPosition;"),i.push("vec4 encodeFloat( const in float v ) {"),i.push("  const vec4 bitShift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0);"),i.push("  const vec4 bitMask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0);"),i.push("  vec4 comp = fract(v * bitShift);"),i.push("  comp -= comp.xxyz * bitMask;"),i.push("  return comp;"),i.push("}"),i.push("void main(void) {"),t){i.push("  bool clippable = (float(vFlags2.x) > 0.0);"),i.push("  if (clippable) {"),i.push("      float dist = 0.0;");for(var s=0;s<e.sectionPlanes.length;s++)i.push("      if (sectionPlaneActive"+s+") {"),i.push("          dist += clamp(dot(-sectionPlaneDir"+s+".xyz, vWorldPosition.xyz - sectionPlanePos"+s+".xyz), 0.0, 1000.0);"),i.push("      }");i.push("      if (dist > 0.0) { discard; }"),i.push("  }")}return i.push("    gl_FragColor = encodeFloat( gl_FragCoord.z); "),i.push("}"),i}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Hi=u.vec4(),Wi=u.vec3(),Yi={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"};class qi{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,a=s.canvas.gl,n=t._state,l=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,l?I(r.viewMatrix,l):r.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,r.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,o.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,o.worldNormalMatrix);const h=s._sectionPlanesState.sectionPlanes.length;if(h>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*h,r=o.renderFlags;for(let t=0;t<h;t++){const s=this._uSectionPlanes[t],o=r.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,o?1:0),o){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Wi);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aNormal&&this._aNormal.bindArrayBuffer(n.normalsBuf),this._aColor&&this._aColor.bindArrayBuffer(n.colorsBuf),this._aMetallicRoughness&&this._aMetallicRoughness.bindArrayBuffer(n.metallicRoughnessBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),n.indicesBuf.bind(),a.drawElements(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uGammaFactor=s.getLocation("gammaFactor"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e<t;e++)switch(o=r[e],o.type){case"dir":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=s.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=s.getLocation("lightDir"+e),this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e)}i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aMetallicRoughness=s.getAttribute("metallicRoughness"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._withSAO&&(this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams")),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(e){const t=V.MAX_TEXTURE_UNITS,i=this._scene,s=i.canvas.gl,r=this._program,o=i._lightsState,a=o.lights,n=i.camera.project;r.bind(),s.uniformMatrix4fv(this._uProjMatrix,!1,n.matrix),this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i._lightsState.getAmbientColorAndIntensity());for(let e=0,t=a.length;e<t;e++){const t=a[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}if(o.reflectionMaps.length>0&&o.reflectionMaps[0].texture&&this._uReflectionMap&&(r.bindTexture(this._uReflectionMap,o.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),o.lightMaps.length>0&&o.lightMaps[0].texture&&this._uLightMap&&(r.bindTexture(this._uLightMap,o.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._withSAO){const r=i.sao;if(r.possible){const i=s.drawingBufferWidth,o=s.drawingBufferHeight;Hi[0]=i,Hi[1]=o,Hi[2]=r.blendCutoff,Hi[3]=r.blendFactor,s.uniform4fv(this._uSAOParams,Hi),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++}}if(i.logarithmicDepthBufferEnabled){const e=2/(Math.log(n.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0,r=t.clippingCaps,o=[];return o.push("// Triangles batching quality draw vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("uniform int renderPass;"),o.push("attribute vec3 position;"),o.push("attribute vec3 normal;"),o.push("attribute vec4 color;"),o.push("attribute vec2 metallicRoughness;"),o.push("attribute vec4 flags;"),o.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&o.push("attribute vec3 offset;"),o.push("uniform mat4 worldMatrix;"),o.push("uniform mat4 worldNormalMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform mat4 viewNormalMatrix;"),o.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("varying float vFragDepth;")),o.push("vec3 octDecode(vec2 oct) {"),o.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push("    if (v.z < 0.0) {"),o.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push("    }"),o.push("    return normalize(v);"),o.push("}"),o.push("varying vec4 vViewPosition;"),o.push("varying vec3 vViewNormal;"),o.push("varying vec4 vColor;"),o.push("varying vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("varying vec3 vWorldNormal;"),s&&(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),r&&o.push("varying vec4 vClipPosition;")),o.push("void main(void) {"),o.push("if (int(flags.x) != renderPass) {"),o.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&o.push("worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition  = viewMatrix * worldPosition; "),o.push("vec4 worldNormal =  worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),o.push("vec3 viewNormal = normalize((viewNormalMatrix * worldNormal).xyz);"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?o.push("vFragDepth = 1.0 + clipPos.w;"):(o.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),o.push("clipPos.z *= clipPos.w;"))),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags2 = flags2;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.sectionPlanes.length>0,o=i.clippingCaps,a=[];a.push("// Triangles batching quality draw fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(a.push("uniform float logDepthBufFC;"),a.push("varying float vFragDepth;")),a.push("varying vec4 vViewPosition;"),a.push("varying vec3 vViewNormal;"),a.push("varying vec4 vColor;"),a.push("varying vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("varying vec3 vWorldNormal;"),a.push("uniform mat4 viewMatrix;"),s.reflectionMaps.length>0&&a.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&a.push("uniform samplerCube lightMap;"),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4      uSAOParams;"),a.push("const float       packUpscale = 256. / 255.;"),a.push("const float       unpackDownScale = 255. / 256.;"),a.push("const vec3        packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );"),a.push("const vec4        unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push("    return dot( v, unPackFactors );"),a.push("}")),a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push("  return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push("  return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push("  return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push("  return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),r){a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),o&&a.push("varying vec4 vClipPosition;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("#define PI 3.14159265359"),a.push("#define RECIPROCAL_PI 0.31830988618"),a.push("#define RECIPROCAL_PI2 0.15915494"),a.push("#define EPSILON 1e-6"),a.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),a.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),a.push("   return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),a.push("}"),a.push("struct IncidentLight {"),a.push("   vec3 color;"),a.push("   vec3 direction;"),a.push("};"),a.push("struct ReflectedLight {"),a.push("   vec3 diffuse;"),a.push("   vec3 specular;"),a.push("};"),a.push("struct Geometry {"),a.push("   vec3 position;"),a.push("   vec3 viewNormal;"),a.push("   vec3 worldNormal;"),a.push("   vec3 viewEyeDir;"),a.push("};"),a.push("struct Material {"),a.push("   vec3    diffuseColor;"),a.push("   float   specularRoughness;"),a.push("   vec3    specularColor;"),a.push("   float   shine;"),a.push("};"),a.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),a.push("   float r = ggxRoughness + 0.0001;"),a.push("   return (2.0 / (r * r) - 2.0);"),a.push("}"),a.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),a.push("   float maxMIPLevelScalar = float( maxMIPLevel );"),a.push("   float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),a.push("   return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),a.push("}"),s.reflectionMaps.length>0&&(a.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),a.push("   float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),a.push("   vec3 envMapColor = "+Yi[s.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),a.push("  return envMapColor;"),a.push("}")),a.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),a.push("   float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),a.push("   return ( 1.0 - specularColor ) * fresnel + specularColor;"),a.push("}"),a.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),a.push("   float a2 = ( alpha * alpha );"),a.push("   float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),a.push("   float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),a.push("   return 1.0 / ( gl * gv );"),a.push("}"),a.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),a.push("   float a2 = ( alpha * alpha );"),a.push("   float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),a.push("   float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),a.push("   return 0.5 / max( gv + gl, EPSILON );"),a.push("}"),a.push("float D_GGX(const in float alpha, const in float dotNH) {"),a.push("   float a2 = ( alpha * alpha );"),a.push("   float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),a.push("   return RECIPROCAL_PI * a2 / ( denom * denom);"),a.push("}"),a.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),a.push("   float alpha = ( roughness * roughness );"),a.push("   vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),a.push("   float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),a.push("   float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),a.push("   float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),a.push("   float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),a.push("   vec3  F = F_Schlick( specularColor, dotLH );"),a.push("   float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),a.push("   float D = D_GGX( alpha, dotNH );"),a.push("   return F * (G * D);"),a.push("}"),a.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),a.push("   float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),a.push("   const vec4 c0 = vec4( -1, -0.0275, -0.572,  0.022);"),a.push("   const vec4 c1 = vec4(  1,  0.0425,   1.04, -0.04);"),a.push("   vec4 r = roughness * c0 + c1;"),a.push("   float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),a.push("   vec2 AB    = vec2(-1.04, 1.04) * a004 + r.zw;"),a.push("   return specularColor * AB.x + AB.y;"),a.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(a.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(a.push("   vec3 irradiance = "+Yi[s.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),a.push("   irradiance *= PI;"),a.push("   vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),a.push("   reflectedLight.diffuse +=  irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(a.push("   vec3 reflectVec             = reflect(geometry.viewEyeDir, geometry.viewNormal);"),a.push("   reflectVec                  = inverseTransformDirection(reflectVec, viewMatrix);"),a.push("   float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),a.push("   vec3 radiance               = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),a.push("   vec3 specularBRDFContrib    = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),a.push("   reflectedLight.specular     += radiance * specularBRDFContrib;")),a.push("}")),a.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.push("   float dotNL     = saturate(dot(geometry.viewNormal, incidentLight.direction));"),a.push("   vec3 irradiance = dotNL * incidentLight.color * PI;"),a.push("   reflectedLight.diffuse  += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),a.push("   reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),a.push("}"),a.push("void main(void) {"),r){a.push("  bool clippable = (float(vFlags2.x) > 0.0);"),a.push("  if (clippable) {"),a.push("  float dist = 0.0;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");o?(a.push("  if (dist > (0.002 * vClipPosition.w)) {"),a.push("      discard;"),a.push("  }"),a.push("  if (dist > 0.0) { "),a.push("      gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("  gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("  return;"),a.push("}")):(a.push("  if (dist > 0.0) { "),a.push("      discard;"),a.push("  }")),a.push("}")}a.push("IncidentLight  light;"),a.push("Material       material;"),a.push("Geometry       geometry;"),a.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),a.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),a.push("float alpha = float(vColor.a) / 255.0;"),a.push("vec3  diffuseColor = rgb;"),a.push("float specularF0 = 1.0;"),a.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),a.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),a.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),a.push("material.diffuseColor      = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),a.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),a.push("material.specularColor     = mix(vec3(dielectricSpecular), diffuseColor, metallic);"),a.push("geometry.position      = vViewPosition.xyz;"),a.push("geometry.viewNormal    = -normalize(vViewNormal);"),a.push("geometry.viewEyeDir    = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&a.push("geometry.worldNormal   = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&a.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("light.direction =  normalize(lightDir"+e+");"):a.push("light.direction =  normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("light.direction =  normalize(lightPos"+e+" - vViewPosition.xyz);"):a.push("light.direction =  normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?a.push("light.direction =  normalize(lightDir"+e+");"):a.push("light.direction =  normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("light.color =  lightColor"+e+".rgb * lightColor"+e+".a;"),a.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return a.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular);"),a.push("vec4 fragColor;"),this._withSAO?(a.push("   float viewportWidth     = uSAOParams[0];"),a.push("   float viewportHeight    = uSAOParams[1];"),a.push("   float blendCutoff       = uSAOParams[2];"),a.push("   float blendFactor       = uSAOParams[3];"),a.push("   vec2 uv                 = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push("   float ambient           = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push("   fragColor               = vec4(outgoingLight.rgb * ambient, alpha);")):a.push("   fragColor            = vec4(outgoingLight.rgb, alpha);"),t&&a.push("fragColor = linearToGamma(fragColor, gammaFactor);"),a.push("gl_FragColor = fragColor;"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Ki{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._colorQualityRenderer&&!this._colorQualityRenderer.getValid()&&(this._colorQualityRenderer.destroy(),this._colorQualityRenderer=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Mi(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new Mi(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRenderer(){return this._colorQualityRenderer||(this._colorQualityRenderer=new qi(this._scene,!1)),this._colorQualityRenderer}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO||(this._colorQualityRendererWithSAO=new qi(this._scene,!0)),this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Ei(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new ji(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Ui(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Si(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Li(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Ti(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ii(this._scene)),this._pickNormalsRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Fi(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new ki(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Xi(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._colorQualityRenderer&&this._colorQualityRenderer.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const Zi={},Qi=V.SUPPORTED_EXTENSIONS.OES_element_index_uint;class $i{constructor(e=5e6){Qi?e>5e6&&(e=5e6):e>65530&&(e=65530),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.metallicRoughness=[],this.normals=[],this.pickColors=[],this.flags=[],this.flags2=[],this.offsets=[],this.indices=[],this.edgeIndices=[]}}const Ji=u.mat4(),es=u.mat4();function ts(e,t,i){const s=e.length,r=new Uint16Array(s),o=t[0],a=t[1],n=t[2],l=t[3]-o,h=t[4]-a,c=t[5]-n,d=65525,p=d/l,_=d/h,f=d/c;for(let t=0;t<s;t+=3)r[t+0]=Math.floor((e[t+0]-o)*p),r[t+1]=Math.floor((e[t+1]-a)*_),r[t+2]=Math.floor((e[t+2]-n)*f);return u.identityMat4(Ji),u.translationMat4v(t,Ji),u.identityMat4(es),u.scalingMat4v([l/d,h/d,c/d],es),u.mulMat4(Ji,es,i),r}function is(e,t,i){let s=e[0]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2])),r=e[1]/(Math.abs(e[0])+Math.abs(e[1])+Math.abs(e[2]));if(e[2]<0){let e=s,t=r;e=(1-Math.abs(r))*(s>=0?1:-1),t=(1-Math.abs(s))*(r>=0?1:-1),s=e,r=t}return new Int8Array([Math[t](127.5*s+(s<0?-1:0)),Math[i](127.5*r+(r<0?-1:0))])}function ss(e,t,i,s){let r=e[t]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2])),o=e[t+1]/(Math.abs(e[t])+Math.abs(e[t+1])+Math.abs(e[t+2]));if(e[t+2]<0){let e=(1-Math.abs(o))*(r>=0?1:-1),t=(1-Math.abs(r))*(o>=0?1:-1);r=e,o=t}return new Int8Array([Math[i](127.5*r+(r<0?-1:0)),Math[s](127.5*o+(o<0?-1:0))])}function rs(e){let t=e[0],i=e[1];t/=t<0?127:128,i/=i<0?127:128;const s=1-Math.abs(t)-Math.abs(i);s<0&&(t=(1-Math.abs(i))*(t>=0?1:-1),i=(1-Math.abs(t))*(i>=0?1:-1));const r=Math.sqrt(t*t+i*i+s*s);return[t/r,i/r,s/r]}function os(e,t){return e[0]*t[0]+e[1]*t[1]+e[2]*t[2]}const as=u.mat4(),ns=u.mat4(),ls=u.vec4([0,0,0,1]),hs=u.vec4([0,0,0,1]),cs=u.vec4([0,0,0,1]),us=u.OBB3();class ds{constructor(e,t){this.sortId=(t.solid,"-solid"),this.layerIndex=t.layerIndex,this._batchingRenderers=function(e){const t=e.id;let i=Zi[t];return i||(i=new Ki(e),Zi[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Zi[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new $i(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new me({positionsBuf:null,offsetsBuf:null,normalsBuf:null,colorsBuf:null,metallicRoughnessBuf:null,flagsBuf:null,flags2Buf:null,indicesBuf:null,edgeIndicesBuf:null,positionsDecodeMatrix:u.mat4(),rtcCenter:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=u.collapseAABB3(),this._portions=[],this._finalized=!1,this._positionsDecodeMatrix=t.positionsDecodeMatrix,this._preCompressed=!!this._positionsDecodeMatrix,t.rtcCenter&&(this._state.rtcCenter=u.vec3(t.rtcCenter)),this.aabb=u.collapseAABB3(),this.solid=!!t.solid}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,i=e.normals,s=e.indices,r=e.edgeIndices,o=e.color,a=e.metallic,n=e.roughness,l=e.colors,h=e.opacity,c=e.meshMatrix,d=e.worldMatrix,p=e.worldAABB,_=e.pickColor,f=this._buffer,g=f.positions.length/3,m=t.length/3,v=t.length;if(this._preCompressed){for(let e=0,i=t.length;e<i;e++)f.positions.push(t[e]);const e=Xe.getPositionsBounds(t),i=Xe.decompressPosition(e.min,this._positionsDecodeMatrix,[]),s=Xe.decompressPosition(e.max,this._positionsDecodeMatrix,[]);p[0]=i[0],p[1]=i[1],p[2]=i[2],p[3]=s[0],p[4]=s[1],p[5]=s[2],d&&(u.AABB3ToOBB3(p,us),u.transformOBB3(d,us),u.OBB3ToAABB3(us,p))}else{const e=f.positions.length;for(let e=0,i=t.length;e<i;e++)f.positions.push(t[e]);if(c)for(let t=e,i=e+v;t<i;t+=3)ls[0]=f.positions[t+0],ls[1]=f.positions[t+1],ls[2]=f.positions[t+2],u.transformPoint4(c,ls,hs),f.positions[t+0]=hs[0],f.positions[t+1]=hs[1],f.positions[t+2]=hs[2],u.expandAABB3Point3(this._modelAABB,hs),d?(u.transformPoint4(d,hs,cs),u.expandAABB3Point3(p,cs)):u.expandAABB3Point3(p,hs);else for(let t=e,i=e+v;t<i;t+=3)ls[0]=f.positions[t+0],ls[1]=f.positions[t+1],ls[2]=f.positions[t+2],u.expandAABB3Point3(this._modelAABB,ls),d?(u.transformPoint4(d,ls,hs),u.expandAABB3Point3(p,hs)):u.expandAABB3Point3(p,ls)}if(this._state.rtcCenter){const e=this._state.rtcCenter;p[0]+=e[0],p[1]+=e[1],p[2]+=e[2],p[3]+=e[0],p[4]+=e[1],p[5]+=e[2]}if(u.expandAABB3(this.aabb,p),i)if(this._preCompressed)for(let e=0,t=i.length;e<t;e++)f.normals.push(i[e]);else{const e=as;c?u.inverseMat4(u.transposeMat4(c,ns),e):u.identityMat4(e,e),function(e,t,i,s,r){let o,a,n,l,h,c,d=new Float32Array([0,0,0,0]),p=new Float32Array([0,0,0,0]);for(c=0;c<i;c+=3)d[0]=t[c],d[1]=t[c+1],d[2]=t[c+2],u.transformVec3(e,d,p),u.normalizeVec3(p,p),n=o=is(p,"floor","floor"),a=rs(o),l=h=os(p,a),o=is(p,"ceil","floor"),a=rs(o),l=os(p,a),l>h&&(n=o,h=l),o=is(p,"floor","ceil"),a=rs(o),l=os(p,a),l>h&&(n=o,h=l),o=is(p,"ceil","ceil"),a=rs(o),l=os(p,a),l>h&&(n=o,h=l),s[r+c+0]=n[0],s[r+c+1]=n[1],s[r+c+2]=0}(e,i,i.length,f.normals,f.normals.length)}if(l)for(let e=0,t=l.length;e<t;e+=3)f.colors.push(255*l[e]),f.colors.push(255*l[e+1]),f.colors.push(255*l[e+2]),f.colors.push(255);else if(o){const e=o[0],t=o[1],i=o[2],s=h,r=null!=a?a:0,l=null!=n?n:255;for(let o=0;o<m;o++)f.colors.push(e),f.colors.push(t),f.colors.push(i),f.colors.push(s),f.metallicRoughness.push(r),f.metallicRoughness.push(l)}if(s)for(let e=0,t=s.length;e<t;e++)f.indices.push(s[e]+g);if(r)for(let e=0,t=r.length;e<t;e++)f.edgeIndices.push(r[e]+g);{const e=f.pickColors.length;for(let t=e,i=e+4*m;t<i;t+=4)f.pickColors.push(_[0]),f.pickColors.push(_[1]),f.pickColors.push(_[2]),f.pickColors.push(_[3])}if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<m;e++)f.offsets.push(0),f.offsets.push(0),f.offsets.push(0);const b=this._portions.length/2;return this._portions.push(g),this._portions.push(m),this._numPortions++,this.model.numPortions++,b}finalize(){if(this._finalized)return void this.model.error("Already finalized");const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0)if(this._preCompressed){e.positionsDecodeMatrix=this._positionsDecodeMatrix;const s=new Uint16Array(i.positions);e.positionsBuf=new ee(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=ts(i.positions,this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ee(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.normals.length>0){const s=new Int8Array(i.normals);let r=!0;e.normalsBuf=new ee(t,t.ARRAY_BUFFER,s,i.normals.length,3,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new ee(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.metallicRoughness.length>0){const s=new Uint8Array(i.metallicRoughness);let r=!1;e.metallicRoughnessBuf=new ee(t,t.ARRAY_BUFFER,s,i.metallicRoughness.length,2,t.STATIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length,r=new Uint8Array(s),o=new Uint8Array(s);let a=!1,n=!0;e.flagsBuf=new ee(t,t.ARRAY_BUFFER,r,r.length,4,t.DYNAMIC_DRAW,a),e.flags2Buf=new ee(t,t.ARRAY_BUFFER,o,o.length,4,t.DYNAMIC_DRAW,n)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new ee(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new ee(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}const s=V.SUPPORTED_EXTENSIONS.OES_element_index_uint;if(i.indices.length>0){const r=s?new Uint32Array(i.indices):new Uint16Array(i.indices);e.indicesBuf=new ee(t,t.ELEMENT_ARRAY_BUFFER,r,i.indices.length,1,t.STATIC_DRAW)}if(i.edgeIndices.length>0){const r=s?new Uint32Array(i.edgeIndices):new Uint16Array(i.edgeIndices);e.edgeIndicesBuf=new ee(t,t.ELEMENT_ARRAY_BUFFER,r,i.edgeIndices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){1&t&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&D&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&S&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&L&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&C&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&B&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),8&t&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),4&t&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i),this._setFlags2(e,t)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";1&t?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&D?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&S?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&L?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&B?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&C?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";4&t?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";8&t?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),a=t[0],n=t[1],l=t[2],h=t[3];for(let e=0;e<r;e+=4)o[e+0]=a,o[e+1]=n,o[e+2]=l,o[e+3]=h;this._state.colorsBuf.setData(o,s,r)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=2*e,r=4*this._portions[s],o=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(o),n=!!(1&t),l=!!(t&S),h=!!(t&D),c=!!(t&L),u=!!(4&t);let d,p;d=!n||u||l?0:i?2:1,p=!n||u?0:c?4:h?3:l?5:0;let _=0;_=!n||u?0:c?9:h?8:l?10:t&B?i?7:6:0;let f=n&&!u&&8&t?11:0;for(let e=0;e<o;e+=4)a[e+0]=d,a[e+1]=p,a[e+2]=_,a[e+3]=f;this._state.flagsBuf.setData(a,r,o)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),a=t&C?255:0;for(let e=0;e<r;e+=4)o[e+0]=a;this._state.flags2Buf.setData(o,s,r)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const i=2*e,s=3*this._portions[i],r=3*this._portions[i+1],o=this._scratchMemory.getFloat32Array(r),a=t[0],n=t[1],l=t[2];for(let e=0;e<r;e+=3)o[e+0]=a,o[e+1]=n,o[e+2]=l;this._state.offsetsBuf.setData(o,s,r)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled?this._batchingRenderers.colorQualityRendererWithSAO&&this._batchingRenderers.colorQualityRendererWithSAO.drawLayer(t,this,1):this._batchingRenderers.colorRendererWithSAO&&this._batchingRenderers.colorRendererWithSAO.drawLayer(t,this,1):t.pbrEnabled&&this.model.pbrEnabled?this._batchingRenderers.colorQualityRenderer&&this._batchingRenderers.colorQualityRenderer.drawLayer(t,this,1):this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,1))}_updateBackfaceCull(e,t){const i=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled?this._batchingRenderers.colorQualityRenderer&&this._batchingRenderers.colorQualityRenderer.drawLayer(t,this,2):this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,2))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.depthRenderer&&this._batchingRenderers.depthRenderer.drawLayer(t,this,1))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.normalsRenderer&&this._batchingRenderers.normalsRenderer.drawLayer(t,this,1))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,5))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,3))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,4))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,6)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&0!==this._numTransparentLayerPortions&&this._batchingRenderers.edgesColorRenderer&&this._batchingRenderers.edgesColorRenderer.drawLayer(t,this,7)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,8)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,9)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.edgesRenderer&&this._batchingRenderers.edgesRenderer.drawLayer(t,this,10)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.occlusionRenderer&&this._batchingRenderers.occlusionRenderer.drawLayer(t,this,1))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.shadowRenderer&&this._batchingRenderers.shadowRenderer.drawLayer(t,this,1))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickMeshRenderer&&this._batchingRenderers.pickMeshRenderer.drawLayer(t,this,11))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickDepthRenderer&&this._batchingRenderers.pickDepthRenderer.drawLayer(t,this,11))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._batchingRenderers.pickNormalsRenderer&&this._batchingRenderers.pickNormalsRenderer.drawLayer(t,this,11))}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.destroy()}}const ps=u.vec4(),_s=u.vec3();class fs{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,_s);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0.bindArrayBuffer(n.modelNormalMatrixCol0Buf),this._aModelNormalMatrixCol1.bindArrayBuffer(n.modelNormalMatrixCol1Buf),this._aModelNormalMatrixCol2.bindArrayBuffer(n.modelNormalMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aNormal.bindArrayBuffer(n.normalsBuf),this._aColor.bindArrayBuffer(n.colorsBuf),l.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),n.indicesBuf.bind(),l.drawElementsInstancedANGLE(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aColor.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(let e=0,t=r.length;e<t;e++)switch(o=r[e],o.type){case"dir":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=null,this._uLightDir[e]=s.getLocation("lightDir"+e);break;case"point":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=null,this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e);break;case"spot":this._uLightColor[e]=s.getLocation("lightColor"+e),this._uLightPos[e]=s.getLocation("lightPos"+e),this._uLightDir[e]=s.getLocation("lightDir"+e),this._uLightAttenuation[e]=s.getLocation("lightAttenuation"+e)}this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aOffset=s.getAttribute("offset"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=s.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=s.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=s.getAttribute("modelNormalMatrixCol2"),this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=t._lightsState.lights,r=t.camera.project;this._program.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),this._uLightAmbient&&i.uniform4fv(this._uLightAmbient,t._lightsState.getAmbientColorAndIntensity());for(let e=0,t=s.length;e<t;e++){const t=s[e];this._uLightColor[e]&&i.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(i.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&i.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&i.uniform3fv(this._uLightDir[e],t.dir)}if(this._withSAO){const s=t.sao;if(s.possible){const t=i.drawingBufferWidth,r=i.drawingBufferHeight;ps[0]=t,ps[1]=r,ps[2]=s.blendCutoff,ps[3]=s.blendFactor,i.uniform4fv(this._uSAOParams,ps),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,0)}}if(t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0;let r,o,a;const n=[];for(n.push("// Instancing geometry drawing vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("#extension GL_EXT_frag_depth : enable"),n.push("uniform int renderPass;"),n.push("attribute vec3 position;"),n.push("attribute vec2 normal;"),n.push("attribute vec4 color;"),n.push("attribute vec4 flags;"),n.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&n.push("attribute vec3 offset;"),n.push("attribute vec4 modelMatrixCol0;"),n.push("attribute vec4 modelMatrixCol1;"),n.push("attribute vec4 modelMatrixCol2;"),n.push("attribute vec4 modelNormalMatrixCol0;"),n.push("attribute vec4 modelNormalMatrixCol1;"),n.push("attribute vec4 modelNormalMatrixCol2;"),n.push("uniform mat4 worldMatrix;"),n.push("uniform mat4 worldNormalMatrix;"),n.push("uniform mat4 viewMatrix;"),n.push("uniform mat4 viewNormalMatrix;"),n.push("uniform mat4 projMatrix;"),n.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(n.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&n.push("varying float vFragDepth;")),n.push("uniform vec4 lightAmbient;"),r=0,o=i.lights.length;r<o;r++)a=i.lights[r],"ambient"!==a.type&&(n.push("uniform vec4 lightColor"+r+";"),"dir"===a.type&&n.push("uniform vec3 lightDir"+r+";"),"point"===a.type&&n.push("uniform vec3 lightPos"+r+";"),"spot"===a.type&&(n.push("uniform vec3 lightPos"+r+";"),n.push("uniform vec3 lightDir"+r+";")));for(n.push("vec3 octDecode(vec2 oct) {"),n.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),n.push("    if (v.z < 0.0) {"),n.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),n.push("    }"),n.push("    return normalize(v);"),n.push("}"),s&&(n.push("varying vec4 vWorldPosition;"),n.push("varying vec4 vFlags2;")),n.push("varying vec4 vColor;"),n.push("void main(void) {"),n.push("if (int(flags.x) != renderPass) {"),n.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),n.push("} else {"),n.push("vec4 worldPosition =  positionsDecodeMatrix * vec4(position, 1.0); "),n.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&n.push("      worldPosition.xyz = worldPosition.xyz + offset;"),n.push("vec4 viewPosition  = viewMatrix * worldPosition; "),n.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),n.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),n.push("vec3 viewNormal = normalize(vec4(viewNormalMatrix * worldNormal).xyz);"),n.push("vec3 reflectedColor = vec3(0.0, 0.0, 0.0);"),n.push("vec3 viewLightDir = vec3(0.0, 0.0, -1.0);"),n.push("float lambertian = 1.0;"),r=0,o=i.lights.length;r<o;r++)if(a=i.lights[r],"ambient"!==a.type){if("dir"===a.type)"view"===a.space?n.push("viewLightDir = normalize(lightDir"+r+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);");else if("point"===a.type)"view"===a.space?n.push("viewLightDir = -normalize(lightPos"+r+" - viewPosition.xyz);"):n.push("viewLightDir = -normalize((viewMatrix * vec4(lightPos"+r+", 0.0)).xyz);");else{if("spot"!==a.type)continue;"view"===a.space?n.push("viewLightDir = normalize(lightDir"+r+");"):n.push("viewLightDir = normalize((viewMatrix * vec4(lightDir"+r+", 0.0)).xyz);")}n.push("lambertian = max(dot(-viewNormal, viewLightDir), 0.0);"),n.push("reflectedColor += lambertian * (lightColor"+r+".rgb * lightColor"+r+".a);")}return n.push("vec3 rgb = (vec3(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0));"),n.push("vColor =  vec4((lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedColor * rgb), float(color.a) / 255.0);"),n.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?n.push("vFragDepth = 1.0 + clipPos.w;"):(n.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),n.push("clipPos.z *= clipPos.w;"))),s&&(n.push("vWorldPosition = worldPosition;"),n.push("vFlags2 = flags2;")),n.push("gl_Position = clipPos;"),n.push("}"),n.push("}"),n}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Instancing geometry drawing fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),this._withSAO&&(s.push("uniform sampler2D uOcclusionTexture;"),s.push("uniform vec4      uSAOParams;"),s.push("const float       packUpscale = 256. / 255.;"),s.push("const float       unpackDownScale = 255. / 256.;"),s.push("const vec3        packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );"),s.push("const vec4        unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),s.push("float unpackRGBToFloat( const in vec4 v ) {"),s.push("    return dot( v, unPackFactors );"),s.push("}")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { "),s.push("      discard;"),s.push("  }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),this._withSAO?(s.push("   float viewportWidth     = uSAOParams[0];"),s.push("   float viewportHeight    = uSAOParams[1];"),s.push("   float blendCutoff       = uSAOParams[2];"),s.push("   float blendFactor       = uSAOParams[3];"),s.push("   vec2 uv                 = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),s.push("   float ambient           = smoothstep(blendCutoff, 1.0, unpackRGBToFloat(texture2D(uOcclusionTexture, uv))) * blendFactor;"),s.push("   gl_FragColor            = vec4(vColor.rgb * ambient, 1.0);")):s.push("    gl_FragColor           = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const gs=u.vec3();class ms{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(t.model.scene),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),5===i){const e=r.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(3===i){const e=r.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(4===i){const e=r.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else a.uniform4fv(this._uColor,u.vec3([1,1,1]));a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,gs);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aFlags.bindArrayBuffer(n.flagsBuf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),n.indicesBuf.bind(),l.drawElementsInstancedANGLE(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uColor=s.getLocation("color"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing fill vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("if (int(flags.y) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Instancing fill fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = color;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const vs=u.vec3(),bs=new Float32Array([0,0,0,1]);class Ps{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),10===i){const e=r.xrayMaterial._state,t=e.edgeColor,i=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(8===i){const e=r.highlightMaterial._state,t=e.edgeColor,i=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(9===i){const e=r.selectedMaterial._state,t=e.edgeColor,i=e.edgeAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else a.uniform4fv(this._uColor,bs);a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,vs);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aFlags&&(this._aFlags.bindArrayBuffer(n.flagsBuf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags.location,1)),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),n.edgeIndicesBuf.bind(),l.drawElementsInstancedANGLE(a.LINES,n.edgeIndicesBuf.numItems,n.edgeIndicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0),this._aFlags&&l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uColor=s.getLocation("color"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Triangles instancing edges vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("uniform vec4 color;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vColor;"),i.push("void main(void) {"),i.push("if (int(flags.z) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(color.r, color.g, color.b, color.a);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const ys=u.vec3();class Ms{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,ys);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aColor.bindArrayBuffer(n.colorsBuf),l.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags&&(this._aFlags.bindArrayBuffer(n.flagsBuf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags.location,1)),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),n.edgeIndicesBuf.bind(),l.drawElementsInstancedANGLE(a.LINES,n.edgeIndicesBuf.numItems,n.edgeIndicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aColor.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0),this._aFlags&&l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aColor=s.getAttribute("color"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Triangles instancing edges vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec4 color;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vColor;"),i.push("void main(void) {"),i.push("if (int(flags.z) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("vColor = vec4(float(color.r*0.5) / 255.0, float(color.g*0.5) / 255.0, float(color.b*0.5) / 255.0, float(color.a) / 255.0);"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry edges drawing fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = vColor;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const xs=u.vec3();class ws{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i);const c=e.pickViewMatrix||o.viewMatrix,u=h?I(c,h):c;if(a.uniformMatrix4fv(this._uViewMatrix,!1,u),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPickColor.bindArrayBuffer(n.pickColorsBuf),l.vertexAttribDivisorANGLE(this._aPickColor.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),n.indicesBuf.bind();const d=r._sectionPlanesState.sectionPlanes.length;if(d>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*d,o=s.renderFlags;for(let t=0;t<d;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,xs);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}l.drawElementsInstancedANGLE(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aPickColor.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._uRenderPass=s.getLocation("renderPass"),this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aPickColor=s.getAttribute("pickColor"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry picking vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 pickColor;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vPickColor;"),i.push("void main(void) {"),i.push("if (int(flags.w) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),i.push("  vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(i.push("  vWorldPosition = worldPosition;"),i.push("  vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry picking fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vPickColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = vPickColor; "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Es=u.vec3();class As{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.canvas.gl,a=t._state,n=this._instanceExt,l=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const h=r.camera;o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);const c=e.pickViewMatrix||h.viewMatrix,u=l?I(c,l):c;if(o.uniformMatrix4fv(this._uViewMatrix,!1,u),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),o.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),o.uniform1f(this._uPickZNear,e.pickZNear),o.uniform1f(this._uPickZFar,e.pickZFar),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}const d=r._sectionPlanesState.sectionPlanes.length;if(d>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*d,a=s.renderFlags;for(let t=0;t<d;t++){const s=this._uSectionPlanes[t],r=a.sectionPlanesActivePerLayer[i+t];if(o.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Es);o.uniform3fv(s.pos,e)}else o.uniform3fv(s.pos,i.pos);o.uniform3fv(s.dir,i.dir)}}}o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),n.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),n.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(a.flags2Buf),n.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(a.offsetsBuf),n.vertexAttribDivisorANGLE(this._aOffset.location,1)),a.indicesBuf.bind(),n.drawElementsInstancedANGLE(o.TRIANGLES,a.indicesBuf.numItems,a.indicesBuf.itemType,0,a.numInstances),n.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),n.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),n.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),n.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&n.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&n.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._aModelMatrixCol0=i.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=i.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=i.getAttribute("modelMatrixCol2"),this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry depth vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vViewPosition;"),i.push("void main(void) {"),i.push("if (int(flags.w) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("  vWorldPosition = worldPosition;"),i.push("  vFlags2 = flags2;")),i.push("  vViewPosition = viewPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry depth fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push("  const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push("  const vec4 bitMask  = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push("  vec4 res = fract(depth * bitShift);"),s.push("  res -= res.xxyz * bitMask;"),s.push("  return res;"),s.push("}"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push("    gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Cs=u.vec3();class Ss{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniform1i(this._uPickInvisible,e.pickInvisible);const c=e.pickViewMatrix||o.viewMatrix,u=h?I(c,h):c;if(a.uniformMatrix4fv(this._uViewMatrix,!1,u),a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const d=r._sectionPlanesState.sectionPlanes.length;if(d>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*d,o=s.renderFlags;for(let t=0;t<d;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,Cs);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0.bindArrayBuffer(n.modelNormalMatrixCol0Buf),this._aModelNormalMatrixCol1.bindArrayBuffer(n.modelNormalMatrixCol1Buf),this._aModelNormalMatrixCol2.bindArrayBuffer(n.modelNormalMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aNormal.bindArrayBuffer(n.normalsBuf),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),n.indicesBuf.bind(),l.drawElementsInstancedANGLE(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=s.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=s.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=s.getAttribute("modelNormalMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry normals vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec2 normal;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("attribute vec4 modelNormalMatrixCol0;"),i.push("attribute vec4 modelNormalMatrixCol1;"),i.push("attribute vec4 modelNormalMatrixCol2;"),i.push("uniform bool pickInvisible;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),i.push("vec3 octDecode(vec2 oct) {"),i.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push("    if (v.z < 0.0) {"),i.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push("    }"),i.push("    return normalize(v);"),i.push("}"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vWorldNormal;"),i.push("void main(void) {"),i.push("if (int(flags.w) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),i.push("  vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),i.push("  vec3 worldNormal = vec3(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2));"),i.push("  vWorldNormal = worldNormal;"),t&&i.push("  vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Batched geometry normals fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec3 vWorldNormal;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("if (sectionPlaneActive"+r+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    gl_FragColor = vec4((vWorldNormal * 0.5) + 0.5, 1.0);"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ds=u.vec3();class Ls{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,Ds);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aColor&&(this._aColor.bindArrayBuffer(n.colorsBuf),l.vertexAttribDivisorANGLE(this._aColor.location,1)),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),n.indicesBuf.bind(),l.drawElementsInstancedANGLE(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),this._aColor&&l.vertexAttribDivisorANGLE(this._aColor.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&i.push("  vWorldPosition = worldPosition;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Instancing occlusion fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push("   gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Bs=u.vec3();class Ts{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,Bs);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),n.indicesBuf.bind(),l.drawElementsInstancedANGLE(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._aModelMatrixCol0=i.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=i.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=i.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry depth drawing vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec2 vHighPrecisionZW;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("vHighPrecisionZW = gl_Position.zw;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Instancing geometry depth drawing fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("precision highp float;"),o.push("precision highp int;"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(o.push("uniform float logDepthBufFC;"),o.push("varying float vFragDepth;")),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture||(o.push("const float   packUpScale = 256. / 255.;"),o.push("const float   unpackDownscale = 255. / 256.;"),o.push("const vec3    packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );"),o.push("const vec4    unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),o.push("const float   shiftRight8 = 1.0 / 256.;"),o.push("vec4 packDepthToRGBA( const in float v ) {"),o.push("    vec4 r = vec4( fract( v * packFactors ), v );"),o.push("    r.yzw -= r.xyz * shiftRight8;"),o.push("    return r * packUpScale;"),o.push("}")),o.push("varying vec2 vHighPrecisionZW;"),o.push("void main(void) {"),r){for(o.push("  bool clippable = (float(vFlags2.x) > 0.0);"),o.push("  if (clippable) {"),o.push("  float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push("   dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("float fragCoordZ = 0.5 * vHighPrecisionZW[0] / vHighPrecisionZW[1] + 0.5;"),V.SUPPORTED_EXTENSIONS.WEBGL_depth_texture?o.push("    gl_FragColor = vec4(vec3(1.0 - fragCoordZ), 1.0); "):o.push("    gl_FragColor = packDepthToRGBA(fragCoordZ); "),o.push("}"),o}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Rs=u.vec3();class Fs{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,Rs);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aNormal.bindArrayBuffer(n.normalsBuf),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),this._aColor.bindArrayBuffer(n.colorsBuf),l.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),n.indicesBuf.bind(),l.drawElementsInstancedANGLE(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aColor.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2&&(this._aFlags2=s.getAttribute("flags2")),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry normals drawing vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec3 normal;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 worldNormalMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 viewNormalMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),i.push("vec3 octDecode(vec2 oct) {"),i.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),i.push("    if (v.z < 0.0) {"),i.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),i.push("    }"),i.push("    return normalize(v);"),i.push("}"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec3 vViewNormal;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),i.push("  vec4 worldNormal    = worldNormalMatrix * vec4(octDecode(normal.xy), 0.0); "),i.push("  vec3 viewNormal     = normalize((viewNormalMatrix * worldNormal).xyz);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("  vViewNormal = viewNormal;"),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Instancing geometry depth drawing fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push("    return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Ns=u.vec3();class Is{constructor(e){this._scene=e,this._hash=this._getHash(),this._lastLightId=null,this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,t)),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(o.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(o.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(o.modelMatrixCol2Buf),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aOffset&&(this._aOffset.bindArrayBuffer(o.offsetsBuf),a.vertexAttribDivisorANGLE(this._aOffset.location,1)),this._aColor.bindArrayBuffer(o.colorsBuf),a.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(o.flagsBuf),a.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(o.flags2Buf),a.vertexAttribDivisorANGLE(this._aFlags2.location,1));const n=s._sectionPlanesState.sectionPlanes.length;if(n>0){const e=s._sectionPlanesState.sectionPlanes,o=t.layerIndex*n,a=i.renderFlags,l=t._state.rtcCenter;for(let t=0;t<n;t++){const i=this._uSectionPlanes[t],s=a.sectionPlanesActivePerLayer[o+t];if(r.uniform1i(i.active,s?1:0),s){const s=e[t];if(l){const e=O(s.dist,s.dir,l,Ns);r.uniform3fv(i.pos,e)}else r.uniform3fv(i.pos,s.pos);r.uniform3fv(i.dir,s.dir)}}}o.indicesBuf.bind(),a.drawElementsInstancedANGLE(r.TRIANGLES,o.indicesBuf.numItems,o.indicesBuf.itemType,0,o.numInstances),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),a.vertexAttribDivisorANGLE(this._aColor.location,0),a.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&a.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&a.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2")}_bindProgram(e,t){const i=this._scene.canvas.gl;this._program.bind(),i.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),i.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastLightId=null}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry shadow drawing vertex shader"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("bool visible      = (float(flags.x) > 0.0);"),i.push("bool transparent  = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("  worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("  vec4 viewPosition  = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("  gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Instancing geometry depth drawing fragment shader"),e.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push("    return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Os=u.vec4(),ks=u.vec3(),Vs={linear:"linearToLinear",sRGB:"sRGBToLinear",gamma:"gammaToLinear"};class js{constructor(e,t){this._scene=e,this._withSAO=t,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){const e=this._scene;return[e.gammaOutput,e._lightsState.getHash(),e._sectionPlanesState.getHash(),this._withSAO?"sao":"nosao"].join(";")}drawLayer(e,t,i){const s=t.model,r=this._scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uViewNormalMatrix,!1,o.viewNormalMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uWorldNormalMatrix,!1,s.worldNormalMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,ks);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aModelNormalMatrixCol0.bindArrayBuffer(n.modelNormalMatrixCol0Buf),this._aModelNormalMatrixCol1.bindArrayBuffer(n.modelNormalMatrixCol1Buf),this._aModelNormalMatrixCol2.bindArrayBuffer(n.modelNormalMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aNormal.bindArrayBuffer(n.normalsBuf),this._aColor.bindArrayBuffer(n.colorsBuf),l.vertexAttribDivisorANGLE(this._aColor.location,1),this._aMetallicRoughness.bindArrayBuffer(n.metallicRoughnessBuf),l.vertexAttribDivisorANGLE(this._aMetallicRoughness.location,1),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),n.indicesBuf.bind(),l.drawElementsInstancedANGLE(a.TRIANGLES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelNormalMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aColor.location,0),l.vertexAttribDivisorANGLE(this._aMetallicRoughness.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._lightsState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uWorldNormalMatrix=s.getLocation("worldNormalMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uViewNormalMatrix=s.getLocation("viewNormalMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uGammaFactor=s.getLocation("gammaFactor"),this._uLightAmbient=s.getLocation("lightAmbient"),this._uLightColor=[],this._uLightDir=[],this._uLightPos=[],this._uLightAttenuation=[];const r=i.lights;let o;for(var a=0,n=r.length;a<n;a++)switch(o=r[a],o.type){case"dir":this._uLightColor[a]=s.getLocation("lightColor"+a),this._uLightPos[a]=null,this._uLightDir[a]=s.getLocation("lightDir"+a);break;case"point":this._uLightColor[a]=s.getLocation("lightColor"+a),this._uLightPos[a]=s.getLocation("lightPos"+a),this._uLightDir[a]=null,this._uLightAttenuation[a]=s.getLocation("lightAttenuation"+a);break;case"spot":this._uLightColor[a]=s.getLocation("lightColor"+a),this._uLightPos[a]=s.getLocation("lightPos"+a),this._uLightDir[a]=s.getLocation("lightDir"+a),this._uLightAttenuation[a]=s.getLocation("lightAttenuation"+a)}i.reflectionMaps.length>0&&(this._uReflectionMap="reflectionMap"),i.lightMaps.length>0&&(this._uLightMap="lightMap"),this._uSectionPlanes=[];for(let t=0,i=e._sectionPlanesState.sectionPlanes.length;t<i;t++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+t),pos:s.getLocation("sectionPlanePos"+t),dir:s.getLocation("sectionPlaneDir"+t)});this._aPosition=s.getAttribute("position"),this._aNormal=s.getAttribute("normal"),this._aColor=s.getAttribute("color"),this._aMetallicRoughness=s.getAttribute("metallicRoughness"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aOffset=s.getAttribute("offset"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._aModelNormalMatrixCol0=s.getAttribute("modelNormalMatrixCol0"),this._aModelNormalMatrixCol1=s.getAttribute("modelNormalMatrixCol1"),this._aModelNormalMatrixCol2=s.getAttribute("modelNormalMatrixCol2"),this._uOcclusionTexture="uOcclusionTexture",this._uSAOParams=s.getLocation("uSAOParams"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(e){const t=V.MAX_TEXTURE_UNITS,i=this._scene,s=i.canvas.gl,r=i._lightsState,o=r.lights,a=i.camera.project;this._program.bind(),s.uniformMatrix4fv(this._uProjMatrix,!1,a.matrix),this._uLightAmbient&&s.uniform4fv(this._uLightAmbient,i._lightsState.getAmbientColorAndIntensity());for(let e=0,t=o.length;e<t;e++){const t=o[e];this._uLightColor[e]&&s.uniform4f(this._uLightColor[e],t.color[0],t.color[1],t.color[2],t.intensity),this._uLightPos[e]&&(s.uniform3fv(this._uLightPos[e],t.pos),this._uLightAttenuation[e]&&s.uniform1f(this._uLightAttenuation[e],t.attenuation)),this._uLightDir[e]&&s.uniform3fv(this._uLightDir[e],t.dir)}if(r.reflectionMaps.length>0&&r.reflectionMaps[0].texture&&this._uReflectionMap&&(this._program.bindTexture(this._uReflectionMap,r.reflectionMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),r.lightMaps.length>0&&r.lightMaps[0].texture&&this._uLightMap&&(this._program.bindTexture(this._uLightMap,r.lightMaps[0].texture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++),this._withSAO){const r=i.sao;if(r.possible){const i=s.drawingBufferWidth,o=s.drawingBufferHeight;Os[0]=i,Os[1]=o,Os[2]=r.blendCutoff,Os[3]=r.blendFactor,s.uniform4fv(this._uSAOParams,Os),this._program.bindTexture(this._uOcclusionTexture,e.occlusionTexture,e.textureUnit),e.textureUnit=(e.textureUnit+1)%t,e.bindTexture++}}if(i.logarithmicDepthBufferEnabled){const e=2/(Math.log(a.far+1)/Math.LN2);s.uniform1f(this._uLogDepthBufFC,e)}this._uGammaFactor&&s.uniform1f(this._uGammaFactor,i.gammaFactor)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState,i=e._lightsState,s=t.sectionPlanes.length>0,r=t.clippingCaps,o=[];return o.push("// Instancing geometry quality drawing vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("uniform int renderPass;"),o.push("attribute vec3 position;"),o.push("attribute vec2 normal;"),o.push("attribute vec4 color;"),o.push("attribute vec2 metallicRoughness;"),o.push("attribute vec4 flags;"),o.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&o.push("attribute vec3 offset;"),o.push("attribute vec4 modelMatrixCol0;"),o.push("attribute vec4 modelMatrixCol1;"),o.push("attribute vec4 modelMatrixCol2;"),o.push("attribute vec4 modelNormalMatrixCol0;"),o.push("attribute vec4 modelNormalMatrixCol1;"),o.push("attribute vec4 modelNormalMatrixCol2;"),o.push("uniform mat4 worldMatrix;"),o.push("uniform mat4 worldNormalMatrix;"),o.push("uniform mat4 viewMatrix;"),o.push("uniform mat4 viewNormalMatrix;"),o.push("uniform mat4 projMatrix;"),o.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(o.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("varying float vFragDepth;")),o.push("vec3 octDecode(vec2 oct) {"),o.push("    vec3 v = vec3(oct.xy, 1.0 - abs(oct.x) - abs(oct.y));"),o.push("    if (v.z < 0.0) {"),o.push("        v.xy = (1.0 - abs(v.yx)) * vec2(v.x >= 0.0 ? 1.0 : -1.0, v.y >= 0.0 ? 1.0 : -1.0);"),o.push("    }"),o.push("    return normalize(v);"),o.push("}"),o.push("varying vec4 vViewPosition;"),o.push("varying vec3 vViewNormal;"),o.push("varying vec4 vColor;"),o.push("varying vec2 vMetallicRoughness;"),i.lightMaps.length>0&&o.push("varying vec3 vWorldNormal;"),s&&(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),r&&o.push("varying vec4 vClipPosition;")),o.push("void main(void) {"),o.push("if (int(flags.x) != renderPass) {"),o.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),o.push("} else {"),o.push("vec4 worldPosition =  positionsDecodeMatrix * vec4(position, 1.0); "),o.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&o.push("      worldPosition.xyz = worldPosition.xyz + offset;"),o.push("vec4 viewPosition  = viewMatrix * worldPosition; "),o.push("vec4 modelNormal = vec4(octDecode(normal.xy), 0.0); "),o.push("vec4 worldNormal = worldNormalMatrix * vec4(dot(modelNormal, modelNormalMatrixCol0), dot(modelNormal, modelNormalMatrixCol1), dot(modelNormal, modelNormalMatrixCol2), 0.0);"),o.push("vec3 viewNormal = vec4(viewNormalMatrix * worldNormal).xyz;"),o.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?o.push("vFragDepth = 1.0 + clipPos.w;"):(o.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),o.push("clipPos.z *= clipPos.w;"))),s&&(o.push("vWorldPosition = worldPosition;"),o.push("vFlags2 = flags2;"),r&&o.push("vClipPosition = clipPos;")),o.push("vViewPosition = viewPosition;"),o.push("vViewNormal = viewNormal;"),o.push("vColor = color;"),o.push("vMetallicRoughness = metallicRoughness;"),i.lightMaps.length>0&&o.push("vWorldNormal = worldNormal.xyz;"),o.push("gl_Position = clipPos;"),o.push("}"),o.push("}"),o}_buildFragmentShader(){const e=this._scene,t=e.gammaOutput,i=e._sectionPlanesState,s=e._lightsState,r=i.sectionPlanes.length>0,o=i.clippingCaps,a=[];a.push("// Instancing geometry quality drawing fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("#extension GL_EXT_frag_depth : enable"),a.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),a.push("precision highp float;"),a.push("precision highp int;"),a.push("#else"),a.push("precision mediump float;"),a.push("precision mediump int;"),a.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(a.push("uniform float logDepthBufFC;"),a.push("varying float vFragDepth;")),this._withSAO&&(a.push("uniform sampler2D uOcclusionTexture;"),a.push("uniform vec4      uSAOParams;"),a.push("const float       packUpscale = 256. / 255.;"),a.push("const float       unpackDownScale = 255. / 256.;"),a.push("const vec3        packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );"),a.push("const vec4        unPackFactors = unpackDownScale / vec4( packFactors, 1. );"),a.push("float unpackRGBAToDepth( const in vec4 v ) {"),a.push("    return dot( v, unPackFactors );"),a.push("}")),s.reflectionMaps.length>0&&a.push("uniform samplerCube reflectionMap;"),s.lightMaps.length>0&&a.push("uniform samplerCube lightMap;"),a.push("uniform vec4 lightAmbient;");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];"ambient"!==t.type&&(a.push("uniform vec4 lightColor"+e+";"),"dir"===t.type&&a.push("uniform vec3 lightDir"+e+";"),"point"===t.type&&a.push("uniform vec3 lightPos"+e+";"),"spot"===t.type&&(a.push("uniform vec3 lightPos"+e+";"),a.push("uniform vec3 lightDir"+e+";")))}if(a.push("uniform float gammaFactor;"),a.push("vec4 linearToLinear( in vec4 value ) {"),a.push("  return value;"),a.push("}"),a.push("vec4 sRGBToLinear( in vec4 value ) {"),a.push("  return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.w );"),a.push("}"),a.push("vec4 gammaToLinear( in vec4 value) {"),a.push("  return vec4( pow( value.xyz, vec3( gammaFactor ) ), value.w );"),a.push("}"),t&&(a.push("vec4 linearToGamma( in vec4 value, in float gammaFactor ) {"),a.push("  return vec4( pow( value.xyz, vec3( 1.0 / gammaFactor ) ), value.w );"),a.push("}")),r){a.push("varying vec4 vWorldPosition;"),a.push("varying vec4 vFlags2;"),o&&a.push("varying vec4 vClipPosition;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)a.push("uniform bool sectionPlaneActive"+e+";"),a.push("uniform vec3 sectionPlanePos"+e+";"),a.push("uniform vec3 sectionPlaneDir"+e+";")}if(a.push("varying vec4 vViewPosition;"),a.push("varying vec3 vViewNormal;"),a.push("varying vec4 vColor;"),a.push("varying vec2 vMetallicRoughness;"),s.lightMaps.length>0&&a.push("varying vec3 vWorldNormal;"),a.push("uniform mat4 viewMatrix;"),a.push("#define PI 3.14159265359"),a.push("#define RECIPROCAL_PI 0.31830988618"),a.push("#define RECIPROCAL_PI2 0.15915494"),a.push("#define EPSILON 1e-6"),a.push("#define saturate(a) clamp( a, 0.0, 1.0 )"),a.push("vec3 inverseTransformDirection(in vec3 dir, in mat4 matrix) {"),a.push("   return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz );"),a.push("}"),a.push("struct IncidentLight {"),a.push("   vec3 color;"),a.push("   vec3 direction;"),a.push("};"),a.push("struct ReflectedLight {"),a.push("   vec3 diffuse;"),a.push("   vec3 specular;"),a.push("};"),a.push("struct Geometry {"),a.push("   vec3 position;"),a.push("   vec3 viewNormal;"),a.push("   vec3 worldNormal;"),a.push("   vec3 viewEyeDir;"),a.push("};"),a.push("struct Material {"),a.push("   vec3    diffuseColor;"),a.push("   float   specularRoughness;"),a.push("   vec3    specularColor;"),a.push("   float   shine;"),a.push("};"),a.push("float GGXRoughnessToBlinnExponent(const in float ggxRoughness) {"),a.push("   float r = ggxRoughness + 0.0001;"),a.push("   return (2.0 / (r * r) - 2.0);"),a.push("}"),a.push("float getSpecularMIPLevel(const in float blinnShininessExponent, const in int maxMIPLevel) {"),a.push("   float maxMIPLevelScalar = float( maxMIPLevel );"),a.push("   float desiredMIPLevel = maxMIPLevelScalar - 0.79248 - 0.5 * log2( ( blinnShininessExponent * blinnShininessExponent ) + 1.0 );"),a.push("   return clamp( desiredMIPLevel, 0.0, maxMIPLevelScalar );"),a.push("}"),s.reflectionMaps.length>0&&(a.push("vec3 getLightProbeIndirectRadiance(const in vec3 reflectVec, const in float blinnShininessExponent, const in int maxMIPLevel) {"),a.push("   float mipLevel = 0.5 * getSpecularMIPLevel(blinnShininessExponent, maxMIPLevel);"),a.push("   vec3 envMapColor = "+Vs[s.reflectionMaps[0].encoding]+"(textureCube(reflectionMap, reflectVec, mipLevel)).rgb;"),a.push("  return envMapColor;"),a.push("}")),a.push("vec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {"),a.push("   float fresnel = exp2( ( -5.55473 * dotLH - 6.98316 ) * dotLH );"),a.push("   return ( 1.0 - specularColor ) * fresnel + specularColor;"),a.push("}"),a.push("float G_GGX_Smith(const in float alpha, const in float dotNL, const in float dotNV) {"),a.push("   float a2 = ( alpha * alpha );"),a.push("   float gl = dotNL + sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),a.push("   float gv = dotNV + sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),a.push("   return 1.0 / ( gl * gv );"),a.push("}"),a.push("float G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {"),a.push("   float a2 = ( alpha * alpha );"),a.push("   float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * ( dotNV * dotNV ) );"),a.push("   float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * ( dotNL * dotNL ) );"),a.push("   return 0.5 / max( gv + gl, EPSILON );"),a.push("}"),a.push("float D_GGX(const in float alpha, const in float dotNH) {"),a.push("   float a2 = ( alpha * alpha );"),a.push("   float denom = ( dotNH * dotNH) * ( a2 - 1.0 ) + 1.0;"),a.push("   return RECIPROCAL_PI * a2 / ( denom * denom);"),a.push("}"),a.push("vec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),a.push("   float alpha = ( roughness * roughness );"),a.push("   vec3 halfDir = normalize( incidentLight.direction + geometry.viewEyeDir );"),a.push("   float dotNL = saturate( dot( geometry.viewNormal, incidentLight.direction ) );"),a.push("   float dotNV = saturate( dot( geometry.viewNormal, geometry.viewEyeDir ) );"),a.push("   float dotNH = saturate( dot( geometry.viewNormal, halfDir ) );"),a.push("   float dotLH = saturate( dot( incidentLight.direction, halfDir ) );"),a.push("   vec3  F = F_Schlick( specularColor, dotLH );"),a.push("   float G = G_GGX_SmithCorrelated( alpha, dotNL, dotNV );"),a.push("   float D = D_GGX( alpha, dotNH );"),a.push("   return F * (G * D);"),a.push("}"),a.push("vec3 BRDF_Specular_GGX_Environment(const in Geometry geometry, const in vec3 specularColor, const in float roughness) {"),a.push("   float dotNV = saturate(dot(geometry.viewNormal, geometry.viewEyeDir));"),a.push("   const vec4 c0 = vec4( -1, -0.0275, -0.572,  0.022);"),a.push("   const vec4 c1 = vec4(  1,  0.0425,   1.04, -0.04);"),a.push("   vec4 r = roughness * c0 + c1;"),a.push("   float a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;"),a.push("   vec2 AB    = vec2(-1.04, 1.04) * a004 + r.zw;"),a.push("   return specularColor * AB.x + AB.y;"),a.push("}"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&(a.push("void computePBRLightMapping(const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),s.lightMaps.length>0&&(a.push("   vec3 irradiance = "+Vs[s.lightMaps[0].encoding]+"(textureCube(lightMap, geometry.worldNormal)).rgb;"),a.push("   irradiance *= PI;"),a.push("   vec3 diffuseBRDFContrib = (RECIPROCAL_PI * material.diffuseColor);"),a.push("   reflectedLight.diffuse += irradiance * diffuseBRDFContrib;")),s.reflectionMaps.length>0&&(a.push("   vec3 reflectVec             = reflect(geometry.viewEyeDir, geometry.viewNormal);"),a.push("   reflectVec                  = inverseTransformDirection(reflectVec, viewMatrix);"),a.push("   float blinnExpFromRoughness = GGXRoughnessToBlinnExponent(material.specularRoughness);"),a.push("   vec3 radiance               = getLightProbeIndirectRadiance(reflectVec, blinnExpFromRoughness, 8);"),a.push("   vec3 specularBRDFContrib    = BRDF_Specular_GGX_Environment(geometry, material.specularColor, material.specularRoughness);"),a.push("   reflectedLight.specular     += radiance * specularBRDFContrib;")),a.push("}")),a.push("void computePBRLighting(const in IncidentLight incidentLight, const in Geometry geometry, const in Material material, inout ReflectedLight reflectedLight) {"),a.push("   float dotNL     = saturate(dot(geometry.viewNormal, incidentLight.direction));"),a.push("   vec3 irradiance = dotNL * incidentLight.color * PI;"),a.push("   reflectedLight.diffuse  += irradiance * (RECIPROCAL_PI * material.diffuseColor);"),a.push("   reflectedLight.specular += irradiance * BRDF_Specular_GGX(incidentLight, geometry, material.specularColor, material.specularRoughness);"),a.push("}"),a.push("void main(void) {"),r){a.push("  bool clippable = (float(vFlags2.x) > 0.0);"),a.push("  if (clippable) {"),a.push("  float dist = 0.0;");for(let e=0,t=i.sectionPlanes.length;e<t;e++)a.push("if (sectionPlaneActive"+e+") {"),a.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),a.push("}");o?(a.push("  if (dist > (0.002 * vClipPosition.w)) {"),a.push("      discard;"),a.push("  }"),a.push("  if (dist > 0.0) { "),a.push("      gl_FragColor=vec4(1.0, 0.0, 0.0, 1.0);"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("  gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("  return;"),a.push("}")):(a.push("  if (dist > 0.0) { "),a.push("      discard;"),a.push("  }")),a.push("}")}a.push("IncidentLight  light;"),a.push("Material       material;"),a.push("Geometry       geometry;"),a.push("ReflectedLight reflectedLight = ReflectedLight(vec3(0.0,0.0,0.0), vec3(0.0,0.0,0.0));"),a.push("vec3 rgb = (vec3(float(vColor.r) / 255.0, float(vColor.g) / 255.0, float(vColor.b) / 255.0));"),a.push("float alpha = float(vColor.a) / 255.0;"),a.push("vec3  diffuseColor = rgb;"),a.push("float specularF0 = 1.0;"),a.push("float metallic = float(vMetallicRoughness.r) / 255.0;"),a.push("float roughness = float(vMetallicRoughness.g) / 255.0;"),a.push("float dielectricSpecular = 0.16 * specularF0 * specularF0;"),a.push("material.diffuseColor      = diffuseColor * (1.0 - dielectricSpecular) * (1.0 - metallic);"),a.push("material.specularRoughness = clamp(roughness, 0.04, 1.0);"),a.push("material.specularColor     = mix(vec3(dielectricSpecular), diffuseColor, metallic);"),a.push("geometry.position      = vViewPosition.xyz;"),a.push("geometry.viewNormal    = -normalize(vViewNormal);"),a.push("geometry.viewEyeDir    = normalize(vViewPosition.xyz);"),s.lightMaps.length>0&&a.push("geometry.worldNormal   = normalize(vWorldNormal);"),(s.lightMaps.length>0||s.reflectionMaps.length>0)&&a.push("computePBRLightMapping(geometry, material, reflectedLight);");for(let e=0,t=s.lights.length;e<t;e++){const t=s.lights[e];if("ambient"!==t.type){if("dir"===t.type)"view"===t.space?a.push("light.direction = normalize(lightDir"+e+");"):a.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);");else if("point"===t.type)"view"===t.space?a.push("light.direction = normalize(lightPos"+e+" - vViewPosition.xyz);"):a.push("light.direction = normalize((viewMatrix * vec4(lightPos"+e+", 0.0)).xyz);");else{if("spot"!==t.type)continue;"view"===t.space?a.push("light.direction = normalize(lightDir"+e+");"):a.push("light.direction = normalize((viewMatrix * vec4(lightDir"+e+", 0.0)).xyz);")}a.push("light.color =  lightColor"+e+".rgb * lightColor"+e+".a;"),a.push("computePBRLighting(light, geometry, material, reflectedLight);")}}return a.push("vec3 outgoingLight = (lightAmbient.rgb * lightAmbient.a * rgb) + (reflectedLight.diffuse) + (reflectedLight.specular);"),a.push("vec4 fragColor;"),this._withSAO?(a.push("   float viewportWidth     = uSAOParams[0];"),a.push("   float viewportHeight    = uSAOParams[1];"),a.push("   float blendCutoff       = uSAOParams[2];"),a.push("   float blendFactor       = uSAOParams[3];"),a.push("   vec2 uv                 = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),a.push("   float ambient           = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),a.push("   fragColor            = vec4(outgoingLight.rgb * ambient, alpha);")):a.push("   fragColor            = vec4(outgoingLight.rgb, alpha);"),t&&a.push("fragColor = linearToGamma(fragColor, gammaFactor);"),a.push("gl_FragColor = fragColor;"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&a.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),a.push("}"),a}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class zs{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._colorRendererWithSAO&&!this._colorRendererWithSAO.getValid()&&(this._colorRendererWithSAO.destroy(),this._colorRendererWithSAO=null),this._colorQualityRenderer&&!this._colorQualityRenderer.getValid()&&(this._colorQualityRenderer.destroy(),this._colorQualityRenderer=null),this._colorQualityRendererWithSAO&&!this._colorQualityRendererWithSAO.getValid()&&(this._colorQualityRendererWithSAO.destroy(),this._colorQualityRendererWithSAO=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._normalsRenderer&&!this._normalsRenderer.getValid()&&(this._normalsRenderer.destroy(),this._normalsRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._edgesRenderer&&!this._edgesRenderer.getValid()&&(this._edgesRenderer.destroy(),this._edgesRenderer=null),this._edgesColorRenderer&&!this._edgesColorRenderer.getValid()&&(this._edgesColorRenderer.destroy(),this._edgesColorRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._pickNormalsRenderer&&!1===this._pickNormalsRenderer.getValid()&&(this._pickNormalsRenderer.destroy(),this._pickNormalsRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new fs(this._scene,!1)),this._colorRenderer}get colorRendererWithSAO(){return this._colorRendererWithSAO||(this._colorRendererWithSAO=new fs(this._scene,!0)),this._colorRendererWithSAO}get colorQualityRenderer(){return this._colorQualityRenderer||(this._colorQualityRenderer=new js(this._scene,!1)),this._colorQualityRenderer}get colorQualityRendererWithSAO(){return this._colorQualityRendererWithSAO||(this._colorQualityRendererWithSAO=new js(this._scene,!0)),this._colorQualityRendererWithSAO}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new ms(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new Ts(this._scene)),this._depthRenderer}get normalsRenderer(){return this._normalsRenderer||(this._normalsRenderer=new Fs(this._scene)),this._normalsRenderer}get edgesRenderer(){return this._edgesRenderer||(this._edgesRenderer=new Ps(this._scene)),this._edgesRenderer}get edgesColorRenderer(){return this._edgesColorRenderer||(this._edgesColorRenderer=new Ms(this._scene)),this._edgesColorRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new ws(this._scene)),this._pickMeshRenderer}get pickNormalsRenderer(){return this._pickNormalsRenderer||(this._pickNormalsRenderer=new Ss(this._scene)),this._pickNormalsRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new As(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Ls(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new Is(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._colorRendererWithSAO&&this._colorRendererWithSAO.destroy(),this._colorQualityRenderer&&this._colorQualityRenderer.destroy(),this._colorQualityRendererWithSAO&&this._colorQualityRendererWithSAO.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._normalsRenderer&&this._normalsRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._edgesRenderer&&this._edgesRenderer.destroy(),this._edgesColorRenderer&&this._edgesColorRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._pickNormalsRenderer&&this._pickNormalsRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const Us={},Gs=V.SUPPORTED_EXTENSIONS.OES_element_index_uint,Xs=new Uint8Array(4),Hs=u.vec4([0,0,0,1]),Ws=u.vec4([0,0,0,1]),Ys=u.vec4([0,0,0,1]),qs=new Float32Array(3);class Ks{constructor(e,t){this.sortId=(t.solid,"-solid"),this.layerIndex=t.layerIndex,this._instancingRenderers=function(e){const t=e.id;let i=Us[t];return i||(i=new zs(e),Us[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Us[t],i._destroy()}))),i}(e.scene),this.model=e,this._aabb=u.collapseAABB3();const i={positionsDecodeMatrix:u.mat4(),numInstances:0,obb:u.OBB3(),rtcCenter:null},s=!!t.positionsDecodeMatrix,r=this.model.scene.canvas.gl;if(t.positions)if(s){let e=!1;i.positionsBuf=new ee(r,r.ARRAY_BUFFER,t.positions,t.positions.length,3,r.STATIC_DRAW,e),i.positionsDecodeMatrix.set(t.positionsDecodeMatrix);let s=u.collapseAABB3();u.expandAABB3Points3(s,t.positions),Xe.decompressAABB(s,i.positionsDecodeMatrix),u.AABB3ToOBB3(s,i.obb)}else{let e=t.positions.length,s=u.collapseAABB3();u.expandAABB3Points3(s,t.positions),u.AABB3ToOBB3(s,i.obb);const o=ts(t.positions,s,i.positionsDecodeMatrix);let a=!1;i.positionsBuf=new ee(r,r.ARRAY_BUFFER,o,e,3,r.STATIC_DRAW,a)}if(t.normals)if(s){const e=!0;i.normalsBuf=new ee(r,r.ARRAY_BUFFER,t.normals,t.normals.length,3,r.STATIC_DRAW,e)}else{const e=function(e){const t=e.length,i=new Int8Array(t);let s,r,o,a;for(let n=0;n<t;n+=3)r=s=ss(e,n,"floor","floor"),rs(s),o=a=os(e,n),s=ss(e,n,"ceil","floor"),rs(s),o=os(e,n),o>a&&(r=s,a=o),s=ss(e,n,"floor","ceil"),rs(s),o=os(e,n),o>a&&(r=s,a=o),s=ss(e,n,"ceil","ceil"),rs(s),o=os(e,n),o>a&&(r=s,a=o),i[n+0]=r[0],i[n+1]=r[1],i[n+2]=0;return new Int8Array(i)}(t.normals),s=!0;i.normalsBuf=new ee(r,r.ARRAY_BUFFER,e,e.length,3,r.STATIC_DRAW,s)}t.indices&&(i.indicesBuf=new ee(r,r.ELEMENT_ARRAY_BUFFER,Gs?new Uint32Array(t.indices):new Uint16Array(t.indices),t.indices.length,1,r.STATIC_DRAW));let o=t.edgeIndices;o||(o=je(t.positions,t.indices,null,t.edgeThreshold||10)),i.edgeIndicesBuf=new ee(r,r.ELEMENT_ARRAY_BUFFER,Gs?new Uint32Array(o):new Uint16Array(o),o.length,1,r.STATIC_DRAW),this._state=new me(i),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.indices?t.indices.length/3:0,this._colors=[],this._metallicRoughness=[],this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[],this._portions=[],t.rtcCenter&&(this._state.rtcCenter=u.vec3(t.rtcCenter)),this._finalized=!1,this.aabb=u.collapseAABB3(),this.solid=!!t.solid}createPortion(e){const t=e.color,i=e.metallic,s=e.roughness,r=e.opacity,o=e.meshMatrix,a=e.worldMatrix,n=e.aabb,l=e.pickColor;if(this._finalized)throw"Already finalized";const h=t[0],c=t[1],d=t[2];t[3],this._colors.push(h),this._colors.push(c),this._colors.push(d),this._colors.push(r),this._metallicRoughness.push(null!=i?i:0),this._metallicRoughness.push(null!=s?s:255),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(o[0]),this._modelMatrixCol0.push(o[4]),this._modelMatrixCol0.push(o[8]),this._modelMatrixCol0.push(o[12]),this._modelMatrixCol1.push(o[1]),this._modelMatrixCol1.push(o[5]),this._modelMatrixCol1.push(o[9]),this._modelMatrixCol1.push(o[13]),this._modelMatrixCol2.push(o[2]),this._modelMatrixCol2.push(o[6]),this._modelMatrixCol2.push(o[10]),this._modelMatrixCol2.push(o[14]);let p=u.transposeMat4(o,u.mat4()),_=u.inverseMat4(p);this._modelNormalMatrixCol0.push(_[0]),this._modelNormalMatrixCol0.push(_[4]),this._modelNormalMatrixCol0.push(_[8]),this._modelNormalMatrixCol0.push(_[12]),this._modelNormalMatrixCol1.push(_[1]),this._modelNormalMatrixCol1.push(_[5]),this._modelNormalMatrixCol1.push(_[9]),this._modelNormalMatrixCol1.push(_[13]),this._modelNormalMatrixCol2.push(_[2]),this._modelNormalMatrixCol2.push(_[6]),this._modelNormalMatrixCol2.push(_[10]),this._modelNormalMatrixCol2.push(_[14]),this._pickColors.push(l[0]),this._pickColors.push(l[1]),this._pickColors.push(l[2]),this._pickColors.push(l[3]),u.collapseAABB3(n);const f=this._state.obb,g=f.length;for(let e=0;e<g;e+=4)Hs[0]=f[e+0],Hs[1]=f[e+1],Hs[2]=f[e+2],u.transformPoint4(o,Hs,Ws),a?(u.transformPoint4(a,Ws,Ys),u.expandAABB3Point3(n,Ys)):u.expandAABB3Point3(n,Ws);if(this._state.rtcCenter){const e=this._state.rtcCenter;n[0]+=e[0],n[1]+=e[1],n[2]+=e[2],n[3]+=e[0],n[4]+=e[1],n[5]+=e[2]}u.expandAABB3(this.aabb,n),this._state.numInstances++;const m=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,m}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._colors.length,i=t;if(t>0){let t=!1;this._state.colorsBuf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(this._metallicRoughness.length>0){const t=new Uint8Array(this._metallicRoughness);let i=!1;this._state.metallicRoughnessBuf=new ee(e,e.ARRAY_BUFFER,t,this._metallicRoughness.length,2,e.STATIC_DRAW,i)}if(i>0){let t=!1,s=!0;this._state.flagsBuf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(i),i,4,e.DYNAMIC_DRAW,t),this._state.flags2Buf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(i),i,4,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._state.modelNormalMatrixCol0Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol0),this._modelNormalMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelNormalMatrixCol1Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol1),this._modelNormalMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelNormalMatrixCol2Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelNormalMatrixCol2),this._modelNormalMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelNormalMatrixCol0=[],this._modelNormalMatrixCol1=[],this._modelNormalMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;this._state.pickColorsBuf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}this._finalized=!0}initFlags(e,t,i){1&t&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&D&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&S&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&L&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&C&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&B&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),8&t&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),4&t&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i),this._setFlags2(e,t)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";1&t?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&D?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&S?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&L?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&B?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&C?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";8&t?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags2(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";4&t?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";Xs[0]=t[0],Xs[1]=t[1],Xs[2]=t[2],Xs[3]=t[3],this._state.colorsBuf.setData(Xs,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(1&t),r=!!(t&S),o=!!(t&D),a=!!(t&L),n=!!(4&t);let l,h;l=!s||n||r?0:i?2:1,h=!s||n?0:a?4:o?3:r?5:0;let c=0;c=!s||n?0:a?9:o?8:r?10:t&B?i?7:6:0;let u=s&&!n&&8&t?11:0;Xs[0]=l,Xs[1]=h,Xs[2]=c,Xs[3]=u,this._state.flagsBuf.setData(Xs,4*e,4)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";const i=t&C?255:0;Xs[0]=i,this._state.flags2Buf.setData(Xs,4*e,4)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(qs[0]=t[0],qs[1]=t[1],qs[2]=t[2],this._state.offsetsBuf.setData(qs,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.withSAO&&this.model.saoEnabled?t.pbrEnabled&&this.model.pbrEnabled?this._instancingRenderers.colorQualityRendererWithSAO&&this._instancingRenderers.colorQualityRendererWithSAO.drawLayer(t,this,1):this._instancingRenderers.colorRendererWithSAO&&this._instancingRenderers.colorRendererWithSAO.drawLayer(t,this,1):t.pbrEnabled&&this.model.pbrEnabled?this._instancingRenderers.colorQualityRenderer&&this._instancingRenderers.colorQualityRenderer.drawLayer(t,this,1):this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,1))}_updateBackfaceCull(e,t){const i=this.model.backfaces||!this.solid||e.sectioned;if(t.backfaces!==i){const e=t.gl;i?e.disable(e.CULL_FACE):e.enable(e.CULL_FACE),t.backfaces=i}}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),t.pbrEnabled&&this.model.pbrEnabled?this._instancingRenderers.colorQualityRenderer&&this._instancingRenderers.colorQualityRenderer.drawLayer(t,this,2):this._instancingRenderers.colorRenderer&&this._instancingRenderers.colorRenderer.drawLayer(t,this,2))}drawDepth(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.depthRenderer&&this._instancingRenderers.depthRenderer.drawLayer(t,this,1))}drawNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.normalsRenderer&&this._instancingRenderers.normalsRenderer.drawLayer(t,this,1))}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,5))}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,3))}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.silhouetteRenderer&&this._instancingRenderers.silhouetteRenderer.drawLayer(t,this,4))}drawEdgesColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,6)}drawEdgesColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numEdgesLayerPortions&&this._instancingRenderers.edgesColorRenderer&&this._instancingRenderers.edgesColorRenderer.drawLayer(t,this,7)}drawEdgesXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,10)}drawEdgesHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,8)}drawEdgesSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._instancingRenderers.edgesRenderer&&this._instancingRenderers.edgesRenderer.drawLayer(t,this,9)}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.occlusionRenderer&&this._instancingRenderers.occlusionRenderer.drawLayer(t,this,1))}drawShadow(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.shadowRenderer&&this._instancingRenderers.shadowRenderer.drawLayer(t,this,1))}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickMeshRenderer&&this._instancingRenderers.pickMeshRenderer.drawLayer(t,this,11))}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickDepthRenderer&&this._instancingRenderers.pickDepthRenderer.drawLayer(t,this,11))}drawPickNormals(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&(this._updateBackfaceCull(e,t),this._instancingRenderers.pickNormalsRenderer&&this._instancingRenderers.pickNormalsRenderer.drawLayer(t,this,11))}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.normalsBuf&&(e.normalsBuf.destroy(),e.normalsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.metallicRoughnessBuf&&(e.metallicRoughnessBuf.destroy(),e.metallicRoughnessBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.modelNormalMatrixCol0Buf&&(e.modelNormalMatrixCol0Buf.destroy(),e.modelNormalMatrixCol0Buf=null),e.modelNormalMatrixCol1Buf&&(e.modelNormalMatrixCol1Buf.destroy(),e.modelNormalMatrixCol1Buf=null),e.modelNormalMatrixCol2Buf&&(e.modelNormalMatrixCol2Buf.destroy(),e.modelNormalMatrixCol2Buf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.edgeIndicesBuf&&(e.edgeIndicesBuf.destroy(),e.edgeIndicessBuf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const Zs=u.vec3();class Qs{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,a=s.canvas.gl,n=t._state,l=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,l?I(r.viewMatrix,l):r.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,o.worldMatrix),a.lineWidth(s.linesMaterial.lineWidth);const h=s._sectionPlanesState.sectionPlanes.length;if(h>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*h,r=o.renderFlags;for(let t=0;t<h;t++){const s=this._uSectionPlanes[t],o=r.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,o?1:0),o){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Zs);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aColor&&this._aColor.bindArrayBuffer(n.colorsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),n.indicesBuf.bind(),a.drawElements(a.LINES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=this._program,r=t.camera.project;if(s.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,r.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(r.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Lines batching color vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vColor;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Lines batching color fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vColor;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return s.push("   gl_FragColor            = vColor;"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const $s=new Float32Array([1,1,1]),Js=u.vec3();class er{constructor(e,t){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),5===i){const e=r.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(3===i){const e=r.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(4===i){const e=r.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else a.uniform4fv(this._uColor,$s);const h=l?I(o.viewMatrix,l):o.viewMatrix;a.uniformMatrix4fv(this._uViewMatrix,!1,h),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.lineWidth(r.linesMaterial.lineWidth);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Js);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),n.indicesBuf.bind(),a.drawElements(a.LINES,n.indicesBuf.numItems,n.indicesBuf.itemType,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uColor=i.getLocation("color"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Lines batching silhouette vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),i.push("uniform vec4 color;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("if (int(flags.y) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Lines batching silhouette fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = color;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class tr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Qs(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new er(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const ir={},sr=V.SUPPORTED_EXTENSIONS.OES_element_index_uint;class rr{constructor(e=5e6){sr?e>5e6&&(e=5e6):e>65530&&(e=65530),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.flags=[],this.flags2=[],this.offsets=[],this.indices=[]}}const or=u.vec4([0,0,0,1]),ar=u.vec4([0,0,0,1]),nr=u.vec4([0,0,0,1]),lr=u.OBB3();class hr{constructor(e,t){this.layerIndex=t.layerIndex,this._batchingRenderers=function(e){const t=e.id;let i=ir[t];return i||(i=new tr(e),ir[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete ir[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new rr(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new me({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,flags2Buf:null,indicesBuf:null,positionsDecodeMatrix:u.mat4(),rtcCenter:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=u.collapseAABB3(),this._portions=[],this._finalized=!1,this._positionsDecodeMatrix=t.positionsDecodeMatrix,this._preCompressed=!!this._positionsDecodeMatrix,t.rtcCenter&&(this._state.rtcCenter=u.vec3(t.rtcCenter)),this.aabb=u.collapseAABB3()}canCreatePortion(e,t){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts&&this._buffer.indices.length+t<this._buffer.maxIndices}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,i=e.indices,s=e.color,r=e.opacity,o=e.meshMatrix,a=e.worldMatrix,n=e.worldAABB;e.pickColor;const l=this._buffer,h=l.positions.length/3,c=t.length/3,d=t.length;if(this._preCompressed){for(let e=0,i=t.length;e<i;e++)l.positions.push(t[e]);const e=Xe.getPositionsBounds(t),i=Xe.decompressPosition(e.min,this._positionsDecodeMatrix,[]),s=Xe.decompressPosition(e.max,this._positionsDecodeMatrix,[]);n[0]=i[0],n[1]=i[1],n[2]=i[2],n[3]=s[0],n[4]=s[1],n[5]=s[2],a&&(u.AABB3ToOBB3(n,lr),u.transformOBB3(a,lr),u.OBB3ToAABB3(lr,n))}else{const e=l.positions.length;for(let e=0,i=t.length;e<i;e++)l.positions.push(t[e]);if(o)for(let t=e,i=e+d;t<i;t+=3)or[0]=l.positions[t+0],or[1]=l.positions[t+1],or[2]=l.positions[t+2],u.transformPoint4(o,or,ar),l.positions[t+0]=ar[0],l.positions[t+1]=ar[1],l.positions[t+2]=ar[2],u.expandAABB3Point3(this._modelAABB,ar),a?(u.transformPoint4(a,ar,nr),u.expandAABB3Point3(n,nr)):u.expandAABB3Point3(n,ar);else for(let t=e,i=e+d;t<i;t+=3)or[0]=l.positions[t+0],or[1]=l.positions[t+1],or[2]=l.positions[t+2],u.expandAABB3Point3(this._modelAABB,or),a?(u.transformPoint4(a,or,ar),u.expandAABB3Point3(n,ar)):u.expandAABB3Point3(n,or)}if(this._state.rtcCenter){const e=this._state.rtcCenter;n[0]+=e[0],n[1]+=e[1],n[2]+=e[2],n[3]+=e[0],n[4]+=e[1],n[5]+=e[2]}if(u.expandAABB3(this.aabb,n),s){const e=s[0],t=s[1],i=s[2],o=r;for(let s=0;s<c;s++)l.colors.push(e),l.colors.push(t),l.colors.push(i),l.colors.push(o)}if(i)for(let e=0,t=i.length;e<t;e++)l.indices.push(i[e]+h);if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<c;e++)l.offsets.push(0),l.offsets.push(0),l.offsets.push(0);const p=this._portions.length/2;return this._portions.push(h),this._portions.push(c),this._numPortions++,this.model.numPortions++,p}finalize(){if(this._finalized)return void this.model.error("Already finalized");const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0)if(this._preCompressed){e.positionsDecodeMatrix=this._positionsDecodeMatrix;const s=new Uint16Array(i.positions);e.positionsBuf=new ee(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=ts(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ee(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new ee(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length,r=new Uint8Array(s),o=new Uint8Array(s);let a=!1,n=!0;e.flagsBuf=new ee(t,t.ARRAY_BUFFER,r,r.length,4,t.DYNAMIC_DRAW,a),e.flags2Buf=new ee(t,t.ARRAY_BUFFER,o,o.length,4,t.DYNAMIC_DRAW,n)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new ee(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}const s=V.SUPPORTED_EXTENSIONS.OES_element_index_uint;if(i.indices.length>0){const r=s?new Uint32Array(i.indices):new Uint16Array(i.indices);e.indicesBuf=new ee(t,t.ELEMENT_ARRAY_BUFFER,r,i.indices.length,1,t.STATIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){1&t&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&D&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&S&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&L&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&C&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&B&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),8&t&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),4&t&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i),this._setFlags2(e,t)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";1&t?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&D?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&S?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&L?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&B?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&C?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";4&t?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";8&t?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),a=t[0],n=t[1],l=t[2],h=t[3];for(let e=0;e<r;e+=4)o[e+0]=a,o[e+1]=n,o[e+2]=l,o[e+3]=h;this._state.colorsBuf.setData(o,s,r)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=2*e,r=4*this._portions[s],o=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(o),n=!!(1&t),l=!!(t&S),h=!!(4&t);let c,u;c=!n||h||l?0:i?2:1,u=!n||h?0:t&L?4:t&D?3:l?5:0;let d=n&&!h&&8&t?11:0;for(let e=0;e<o;e+=4)a[e+0]=c,a[e+1]=u,a[e+2]=0,a[e+3]=d;this._state.flagsBuf.setData(a,r,o)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),a=t&C?255:0;for(let e=0;e<r;e+=4)o[e+0]=a;this._state.flags2Buf.setData(o,s,r)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const i=2*e,s=3*this._portions[i],r=3*this._portions[i+1],o=this._scratchMemory.getFloat32Array(r),a=t[0],n=t[1],l=t[2];for(let e=0;e<r;e+=3)o[e+0]=a,o[e+1]=n,o[e+2]=l;this._state.offsetsBuf.setData(o,s,r)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,1)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._batchingRenderers.colorRenderer&&this._batchingRenderers.colorRenderer.drawLayer(t,this,2)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,5)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,3)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._batchingRenderers.silhouetteRenderer&&this._batchingRenderers.silhouetteRenderer.drawLayer(t,this,4)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e){}drawPickDepths(e){}drawPickNormals(e){}drawOcclusion(e){}drawShadow(e){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.destroy()}}const cr=u.vec3();class ur{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.lineWidth(r.linesMaterial.lineWidth);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,cr);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aColor.bindArrayBuffer(n.colorsBuf),l.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),n.indicesBuf.bind(),l.drawElementsInstancedANGLE(a.LINES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aColor.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._aOffset=i.getAttribute("offset"),this._aModelMatrixCol0=i.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=i.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=i.getAttribute("modelMatrixCol2"),this._uOcclusionTexture="uOcclusionTexture",e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Lines instancing color vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),i.push("uniform vec4 lightAmbient;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("varying vec4 vColor;"),i.push("void main(void) {"),i.push("if (int(flags.x) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition =  positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),i.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0,  float(color.a) / 255.0);"),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Lines instancing color fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(o.push("uniform float logDepthBufFC;"),o.push("varying float vFragDepth;")),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("varying vec4 vColor;"),o.push("void main(void) {"),r){for(o.push("  bool clippable = (float(vFlags2.x) > 0.0);"),o.push("  if (clippable) {"),o.push("  float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push("   dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return this._withSAO?(o.push("   float viewportWidth     = uSAOParams[0];"),o.push("   float viewportHeight    = uSAOParams[1];"),o.push("   float blendCutoff       = uSAOParams[2];"),o.push("   float blendFactor       = uSAOParams[3];"),o.push("   vec2 uv                 = vec2(gl_FragCoord.x / viewportWidth, gl_FragCoord.y / viewportHeight);"),o.push("   float ambient           = smoothstep(blendCutoff, 1.0, unpackRGBAToDepth(texture2D(uOcclusionTexture, uv))) * blendFactor;"),o.push("   gl_FragColor            = vec4(vColor.rgb * ambient, vColor.a);")):o.push("    gl_FragColor           = vColor;"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const dr=u.vec3();class pr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter;if(!this._program&&(this._allocate(t.model.scene),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),5===i){const e=r.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(3===i){const e=r.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(4===i){const e=r.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else a.uniform4fv(this._uColor,u.vec3([1,1,1]));a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.lineWidth(r.linesMaterial.lineWidth);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,o=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,dr);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aFlags.bindArrayBuffer(n.flagsBuf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),n.indicesBuf.bind(),l.drawElementsInstancedANGLE(a.LINES,n.indicesBuf.numItems,n.indicesBuf.itemType,0,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uColor=s.getLocation("color"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Lines instancing silhouette vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("#extension GL_EXT_frag_depth : enable"),i.push("uniform int renderPass;"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 worldMatrix;"),i.push("uniform mat4 viewMatrix;"),i.push("uniform mat4 projMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),e.logarithmicDepthBufferEnabled&&(i.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&i.push("varying float vFragDepth;")),i.push("uniform vec4 color;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("if (int(flags.y) != renderPass) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?i.push("vFragDepth = 1.0 + clipPos.w;"):(i.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),i.push("clipPos.z *= clipPos.w;"))),i.push("gl_Position = clipPos;"),i.push("}"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Lines instancing silhouette fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("void main(void) {"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = color;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class _r{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new ur(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new pr(this._scene)),this._silhouetteRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy()}}const fr={},gr=V.SUPPORTED_EXTENSIONS.OES_element_index_uint,mr=new Uint8Array(4),vr=u.vec4([0,0,0,1]),br=u.vec4([0,0,0,1]),Pr=u.vec4([0,0,0,1]),yr=new Float32Array(3);class Mr{constructor(e,t){this.sortId="LinesInstancingLayer",this.layerIndex=t.layerIndex,this._linesInstancingRenderers=function(e){const t=e.id;let i=fr[t];return i||(i=new _r(e),fr[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete fr[t],i._destroy()}))),i}(e.scene),this.model=e,this._aabb=u.collapseAABB3();const i=e.scene.canvas.gl,s={positionsDecodeMatrix:u.mat4(),numInstances:0,obb:u.OBB3(),rtcCenter:null},r=!!t.positionsDecodeMatrix;if(t.positions)if(r){let e=!1;s.positionsBuf=new ee(i,i.ARRAY_BUFFER,t.positions,t.positions.length,3,i.STATIC_DRAW,e),s.positionsDecodeMatrix.set(t.positionsDecodeMatrix);let r=u.collapseAABB3();u.expandAABB3Points3(r,t.positions),Xe.decompressAABB(r,s.positionsDecodeMatrix),u.AABB3ToOBB3(r,s.obb)}else{let e=t.positions.length,r=u.collapseAABB3();u.expandAABB3Points3(r,t.positions),u.AABB3ToOBB3(r,s.obb);const o=ts(t.positions,r,s.positionsDecodeMatrix);let a=!1;s.positionsBuf=new ee(i,i.ARRAY_BUFFER,o,e,3,i.STATIC_DRAW,a)}t.indices&&(s.indicesBuf=new ee(i,i.ELEMENT_ARRAY_BUFFER,gr?new Uint32Array(t.indices):new Uint16Array(t.indices),t.indices.length,1,i.STATIC_DRAW)),this._state=new me(s),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this.numIndices=t.indices?t.indices.length/3:0,this._colors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],t.rtcCenter&&(this._state.rtcCenter=u.vec3(t.rtcCenter)),this._finalized=!1,this.aabb=u.collapseAABB3()}createPortion(e){const t=e.color,i=e.opacity,s=e.meshMatrix,r=e.worldMatrix,o=e.aabb;if(this._finalized)throw"Already finalized";const a=t[0],n=t[1],l=t[2];t[3],this._colors.push(a),this._colors.push(n),this._colors.push(l),this._colors.push(i),this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(s[0]),this._modelMatrixCol0.push(s[4]),this._modelMatrixCol0.push(s[8]),this._modelMatrixCol0.push(s[12]),this._modelMatrixCol1.push(s[1]),this._modelMatrixCol1.push(s[5]),this._modelMatrixCol1.push(s[9]),this._modelMatrixCol1.push(s[13]),this._modelMatrixCol2.push(s[2]),this._modelMatrixCol2.push(s[6]),this._modelMatrixCol2.push(s[10]),this._modelMatrixCol2.push(s[14]),u.collapseAABB3(o);const h=this._state.obb,c=h.length;for(let e=0;e<c;e+=4)vr[0]=h[e+0],vr[1]=h[e+1],vr[2]=h[e+2],u.transformPoint4(s,vr,br),r?(u.transformPoint4(r,br,Pr),u.expandAABB3Point3(o,Pr)):u.expandAABB3Point3(o,br);if(this._state.rtcCenter){const e=this._state.rtcCenter;o[0]+=e[0],o[1]+=e[1],o[2]+=e[2],o[3]+=e[0],o[4]+=e[1],o[5]+=e[2]}u.expandAABB3(this.aabb,o),this._state.numInstances++;const d=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,d}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._colors.length,i=t;if(t>0){let t=!1;this._state.colorsBuf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(this._colors),this._colors.length,4,e.DYNAMIC_DRAW,t),this._colors=[]}if(i>0){let t=!1,s=!0;this._state.flagsBuf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(i),i,4,e.DYNAMIC_DRAW,t),this._state.flags2Buf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(i),i,4,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}this._finalized=!0}initFlags(e,t,i){1&t&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&D&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&S&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&L&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&C&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&B&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),8&t&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),4&t&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i),this._setFlags2(e,t)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";1&t?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&D?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&S?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&L?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&B?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&C?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";8&t?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags2(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";4&t?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";mr[0]=t[0],mr[1]=t[1],mr[2]=t[2],mr[3]=t[3],this._state.colorsBuf.setData(mr,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(1&t),r=!!(t&S),o=!!(t&D),a=!!(t&L),n=!!(4&t);let l,h;l=!s||n||r?0:i?2:1,h=!s||n?0:a?4:o?3:r?5:0;let c=0;c=!s||n?0:a?9:o?8:r?10:t&B?i?7:6:0;let u=s&&!n&&8&t?11:0;mr[0]=l,mr[1]=h,mr[2]=c,mr[3]=u,this._state.flagsBuf.setData(mr,4*e,4)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";const i=t&C?255:0;mr[0]=i,this._state.flags2Buf.setData(mr,4*e,4)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(yr[0]=t[0],yr[1]=t[1],yr[2]=t[2],this._state.offsetsBuf.setData(yr,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,1)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._linesInstancingRenderers.colorRenderer&&this._linesInstancingRenderers.colorRenderer.drawLayer(t,this,2)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,5)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,3)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._linesInstancingRenderers.silhouetteRenderer&&this._linesInstancingRenderers.silhouetteRenderer.drawLayer(t,this,4)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesXRayed(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawOcclusion(e,t){}drawShadow(e,t){}drawPickMesh(e,t){}drawPickDepths(e,t){}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.indicesBuf&&(e.indicesBuf.destroy(),e.indicessBuf=null),e.destroy()}}const xr=u.vec3();class wr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=this._scene,r=s.camera,o=t.model,a=s.canvas.gl,n=t._state,l=t._state.rtcCenter,h=s.pointsMaterial;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,l?I(r.viewMatrix,l):r.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,o.worldMatrix);const c=s._sectionPlanesState.sectionPlanes.length;if(c>0){const e=s._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,r=o.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],o=r.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,o?1:0),o){const i=e[t];if(l){const e=O(i.dist,i.dir,l,xr);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aColor&&this._aColor.bindArrayBuffer(n.colorsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),a.uniform1f(this._uPointSize,h.pointSize);const u="ortho"===s.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*s.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,u),a.drawArrays(a.POINTS,0,n.positionsBuf.numItems)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader(e)),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._uPointSize=i.getLocation("pointSize"),this._uNearPlaneHeight=i.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=this._program,s=e.camera.project;if(i.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial,s=[];return s.push("// Points batching color vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec4 vColor;"),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition  = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Points batching color fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }")),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("  if (dist > 0.0) { discard; }"),s.push("}")}return s.push("   gl_FragColor = vColor;"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Er=new Float32Array([1,1,1]),Ar=u.vec3();class Cr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter,h=r.pointsMaterial._state;if(!this._program&&(this._allocate(),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),5===i){const e=r.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(3===i){const e=r.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(4===i){const e=r.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else a.uniform4fv(this._uColor,Er);const c=l?I(o.viewMatrix,l):o.viewMatrix;a.uniformMatrix4fv(this._uViewMatrix,!1,c),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const u=r._sectionPlanesState.sectionPlanes.length;if(u>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*u,o=s.renderFlags;for(let t=0;t<u;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Ar);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),a.uniform1f(this._uPointSize,h.pointSize);const d="ortho"===r.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,d),a.drawArrays(a.POINTS,0,n.positionsBuf.numItems)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uColor=i.getLocation("color"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._uPointSize=i.getLocation("pointSize"),this._uNearPlaneHeight=i.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points batching silhouette vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform vec4 color;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("if (int(flags.y) != renderPass) {"),s.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Points batching silhouette vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(o.push("uniform float logDepthBufFC;"),o.push("varying float vFragDepth;")),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("uniform vec4 color;"),o.push("void main(void) {"),e.pointsMaterial.roundPoints&&(o.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("  float r = dot(cxy, cxy);"),o.push("  if (r > 1.0) {"),o.push("       discard;"),o.push("  }")),r){for(o.push("  bool clippable = (float(vFlags2.x) > 0.0);"),o.push("  if (clippable) {"),o.push("  float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push("   dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("  if (dist > 0.0) { discard; }"),o.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("gl_FragColor = color;"),o.push("}"),o}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Sr=u.vec3();class Dr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter,h=r.pointsMaterial._state;this._program||this._allocate(t),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const c=e.pickViewMatrix||o.viewMatrix,u=l?I(c,l):c;if(a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),a.uniformMatrix4fv(this._uViewMatrix,!1,u),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}const d=r._sectionPlanesState.sectionPlanes.length;if(d>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*d,o=s.renderFlags;for(let t=0;t<d;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Sr);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),this._aPickColor&&this._aPickColor.bindArrayBuffer(n.pickColorsBuf),a.uniform1f(this._uPointSize,h.pointSize);const p="ortho"===r.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,p),a.drawArrays(a.POINTS,0,n.positionsBuf.numItems)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aPickColor=i.getAttribute("pickColor"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._uPointSize=i.getLocation("pointSize"),this._uNearPlaneHeight=i.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points batching pick mesh vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("attribute vec4 pickColor;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec4 vPickColor;"),s.push("void main(void) {"),s.push("if (int(flags.w) != renderPass) {"),s.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("  } else {"),s.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),s.push("      vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push("      vWorldPosition = worldPosition;"),s.push("      vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push("  }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Points batching pick mesh vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("uniform bool sectionPlaneActive"+r+";"),s.push("uniform vec3 sectionPlanePos"+r+";"),s.push("uniform vec3 sectionPlaneDir"+r+";")}if(s.push("varying vec4 vPickColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }")),i){for(s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;"),r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("   gl_FragColor = vPickColor; "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Lr=u.vec3();class Br{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=t._state.rtcCenter,h=r.pointsMaterial._state;this._program||this._allocate(),e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniform1i(this._uPickInvisible,e.pickInvisible);const c=e.pickViewMatrix||o.viewMatrix,u=l?I(c,l):c;if(a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uViewMatrix,!1,u),a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),a.uniform1f(this._uPickZNear,e.pickZNear),a.uniform1f(this._uPickZFar,e.pickZFar),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,t)}const d=r._sectionPlanesState.sectionPlanes.length;if(d>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*d,o=s.renderFlags;for(let t=0;t<d;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Lr);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(n.offsetsBuf),this._aFlags&&this._aFlags.bindArrayBuffer(n.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(n.flags2Buf),a.uniform1f(this._uPointSize,h.pointSize);const p="ortho"===r.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,p),a.drawArrays(a.POINTS,0,n.positionsBuf.numItems)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),this._uPointSize=i.getLocation("pointSize"),this._uNearPlaneHeight=i.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points batched pick depth vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec4 vViewPosition;"),s.push("void main(void) {"),s.push("if (int(flags.w) != renderPass) {"),s.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("  } else {"),s.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(s.push("      vWorldPosition = worldPosition;"),s.push("      vFlags2 = flags2;")),s.push("vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("gl_PointSize += 10.0;"),s.push("  }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Points batched pick depth fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push("  const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push("  const vec4 bitMask  = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push("  vec4 res = fract(depth * bitShift);"),s.push("  res -= res.xxyz * bitMask;"),s.push("  return res;"),s.push("}"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }")),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(var r=0;r<t.sectionPlanes.length;r++)s.push("      if (sectionPlaneActive"+r+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+r+".xyz, vWorldPosition.xyz - sectionPlanePos"+r+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push("    gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Tr=u.vec3();class Rr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.canvas.gl,a=t._state,n=r.camera,l=t._state.rtcCenter,h=r.pointsMaterial._state;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),o.uniform1i(this._uRenderPass,i),o.uniformMatrix4fv(this._uViewMatrix,!1,l?I(n.viewMatrix,l):n.viewMatrix),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const c=r._sectionPlanesState.sectionPlanes.length;if(c>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*c,a=s.renderFlags;for(let t=0;t<c;t++){const s=this._uSectionPlanes[t],r=a.sectionPlanesActivePerLayer[i+t];if(o.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Tr);o.uniform3fv(s.pos,e)}else o.uniform3fv(s.pos,i.pos);o.uniform3fv(s.dir,i.dir)}}}o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aOffset&&this._aOffset.bindArrayBuffer(a.offsetsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),this._aFlags2&&this._aFlags2.bindArrayBuffer(a.flags2Buf),o.uniform1f(this._uPointSize,h.pointSize);const u="ortho"===r.camera.projection?1:o.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));o.uniform1f(this._uNearPlaneHeight,u),o.drawArrays(o.POINTS,0,a.positionsBuf.numItems)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._uPointSize=i.getLocation("pointSize"),this._uNearPlaneHeight=i.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points batching occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("  } else {"),s.push("      vec4 worldPosition = worldMatrix * (positionsDecodeMatrix * vec4(position, 1.0)); "),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("      vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(s.push("      vWorldPosition = worldPosition;"),s.push("      vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("  gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("  }"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Points batching occlusion fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }")),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("      float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("      if (sectionPlaneActive"+e+") {"),s.push("          dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("      }");s.push("      if (dist > 0.0) { discard; }"),s.push("  }")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("   gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class Fr{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new wr(this._scene)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new Cr(this._scene)),this._silhouetteRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Dr(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new Br(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new Rr(this._scene)),this._occlusionRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy()}}const Nr={},Ir=V.SUPPORTED_EXTENSIONS.OES_element_index_uint;class Or{constructor(e=5e6){Ir?e>5e6&&(e=5e6):e>65530&&(e=65530),this.maxVerts=e,this.maxIndices=3*e,this.positions=[],this.colors=[],this.pickColors=[],this.flags=[],this.flags2=[],this.offsets=[]}}const kr=u.vec4(),Vr=u.vec4(),jr=u.vec4([0,0,0,1]),zr=u.vec4([0,0,0,1]),Ur=u.vec4([0,0,0,1]),Gr=u.OBB3();class Xr{constructor(e,t){this.sortId="PointsBatchingLayer",this.layerIndex=t.layerIndex,this._pointsBatchingRenderers=function(e){const t=e.id;let i=Nr[t];return i||(i=new Fr(e),Nr[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete Nr[t],i._destroy()}))),i}(e.scene),this.model=e,this._buffer=new Or(t.maxGeometryBatchSize),this._scratchMemory=t.scratchMemory,this._state=new me({positionsBuf:null,offsetsBuf:null,colorsBuf:null,flagsBuf:null,flags2Buf:null,positionsDecodeMatrix:u.mat4(),rtcCenter:null}),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numSelectedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numClippableLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._modelAABB=u.collapseAABB3(),this._portions=[],this._finalized=!1,this._positionsDecodeMatrix=t.positionsDecodeMatrix,this._preCompressed=!!this._positionsDecodeMatrix,t.rtcCenter&&(this._state.rtcCenter=u.vec3(t.rtcCenter)),this.aabb=u.collapseAABB3()}canCreatePortion(e){if(this._finalized)throw"Already finalized";return this._buffer.positions.length+e<3*this._buffer.maxVerts}createPortion(e){if(this._finalized)throw"Already finalized";const t=e.positions,i=e.color,s=e.colors,r=e.opacity,o=e.meshMatrix,a=e.worldMatrix,n=e.worldAABB,l=e.pickColor,h=this._buffer,c=h.positions.length/3,d=t.length/3,p=t.length;if(this._preCompressed){for(let e=0,i=t.length;e<i;e++)h.positions.push(t[e]);const e=Xe.getPositionsBounds(t),i=Xe.decompressPosition(e.min,this._positionsDecodeMatrix,kr),s=Xe.decompressPosition(e.max,this._positionsDecodeMatrix,Vr);n[0]=i[0],n[1]=i[1],n[2]=i[2],n[3]=s[0],n[4]=s[1],n[5]=s[2],a&&(u.AABB3ToOBB3(n,Gr),u.transformOBB3(a,Gr),u.OBB3ToAABB3(Gr,n))}else{const e=h.positions.length;for(let e=0,i=t.length;e<i;e++)h.positions.push(t[e]);if(o)for(let t=e,i=e+p;t<i;t+=3)jr[0]=h.positions[t+0],jr[1]=h.positions[t+1],jr[2]=h.positions[t+2],u.transformPoint4(o,jr,zr),h.positions[t+0]=zr[0],h.positions[t+1]=zr[1],h.positions[t+2]=zr[2],u.expandAABB3Point3(this._modelAABB,zr),a?(u.transformPoint4(a,zr,Ur),u.expandAABB3Point3(n,Ur)):u.expandAABB3Point3(n,zr);else for(let t=e,i=e+p;t<i;t+=3)jr[0]=h.positions[t+0],jr[1]=h.positions[t+1],jr[2]=h.positions[t+2],u.expandAABB3Point3(this._modelAABB,jr),a?(u.transformPoint4(a,jr,zr),u.expandAABB3Point3(n,zr)):u.expandAABB3Point3(n,jr)}if(this._state.rtcCenter){const e=this._state.rtcCenter;n[0]+=e[0],n[1]+=e[1],n[2]+=e[2],n[3]+=e[0],n[4]+=e[1],n[5]+=e[2]}if(u.expandAABB3(this.aabb,n),s)for(let e=0,t=s.length;e<t;e+=3)h.colors.push(255*s[e]),h.colors.push(255*s[e+1]),h.colors.push(255*s[e+2]),h.colors.push(255);else if(i){const e=i[0],t=i[1],s=i[2],o=r;for(let i=0;i<d;i++)h.colors.push(e),h.colors.push(t),h.colors.push(s),h.colors.push(o)}{const e=h.pickColors.length;for(let t=e,i=e+4*d;t<i;t+=4)h.pickColors.push(l[0]),h.pickColors.push(l[1]),h.pickColors.push(l[2]),h.pickColors.push(l[3])}if(this.model.scene.entityOffsetsEnabled)for(let e=0;e<d;e++)h.offsets.push(0),h.offsets.push(0),h.offsets.push(0);const _=this._portions.length/2;return this._portions.push(c),this._portions.push(d),this._numPortions++,this.model.numPortions++,_}finalize(){if(this._finalized)return void this.model.error("Already finalized");const e=this._state,t=this.model.scene.canvas.gl,i=this._buffer;if(i.positions.length>0)if(this._preCompressed){e.positionsDecodeMatrix=this._positionsDecodeMatrix;const s=new Uint16Array(i.positions);e.positionsBuf=new ee(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}else{const s=ts(new Float32Array(i.positions),this._modelAABB,e.positionsDecodeMatrix);e.positionsBuf=new ee(t,t.ARRAY_BUFFER,s,i.positions.length,3,t.STATIC_DRAW)}if(i.colors.length>0){const s=new Uint8Array(i.colors);let r=!1;e.colorsBuf=new ee(t,t.ARRAY_BUFFER,s,i.colors.length,4,t.DYNAMIC_DRAW,r)}if(i.colors.length>0){const s=i.colors.length,r=new Uint8Array(s),o=new Uint8Array(s);let a=!1,n=!0;e.flagsBuf=new ee(t,t.ARRAY_BUFFER,r,r.length,4,t.DYNAMIC_DRAW,a),e.flags2Buf=new ee(t,t.ARRAY_BUFFER,o,o.length,4,t.DYNAMIC_DRAW,n)}if(i.pickColors.length>0){const s=new Uint8Array(i.pickColors);let r=!1;e.pickColorsBuf=new ee(t,t.ARRAY_BUFFER,s,i.pickColors.length,4,t.STATIC_DRAW,r)}if(this.model.scene.entityOffsetsEnabled&&i.offsets.length>0){const s=new Float32Array(i.offsets);e.offsetsBuf=new ee(t,t.ARRAY_BUFFER,s,i.offsets.length,3,t.DYNAMIC_DRAW)}this._buffer=null,this._finalized=!0}initFlags(e,t,i){1&t&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&D&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&S&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&L&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&C&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),8&t&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),4&t&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i),this._setFlags2(e,t)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";1&t?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&D?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&S?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&L?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized"}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&C?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";4&t?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";8&t?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),a=t[0],n=t[1],l=t[2],h=t[3];for(let e=0;e<r;e+=4)o[e+0]=a,o[e+1]=n,o[e+2]=l,o[e+3]=h;this._state.colorsBuf.setData(o,s,r)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=2*e,r=4*this._portions[s],o=4*this._portions[s+1],a=this._scratchMemory.getUInt8Array(o),n=!!(1&t),l=!!(t&S),h=!!(4&t);let c,u;c=!n||h||l?0:i?2:1,u=!n||h?0:t&L?4:t&D?3:l?5:0;let d=n&&!h&&8&t?11:0;for(let e=0;e<o;e+=4)a[e+0]=c,a[e+1]=u,a[e+2]=0,a[e+3]=d;this._state.flagsBuf.setData(a,r,o)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";const i=2*e,s=4*this._portions[i],r=4*this._portions[i+1],o=this._scratchMemory.getUInt8Array(r),a=t&C?255:0;for(let e=0;e<r;e+=4)o[e+0]=a;this._state.flags2Buf.setData(o,s,r)}setOffset(e,t){if(!this._finalized)throw"Not finalized";if(!this.model.scene.entityOffsetsEnabled)return void this.model.error("Entity#offset not enabled for this Viewer");const i=2*e,s=3*this._portions[i],r=3*this._portions[i+1],o=this._scratchMemory.getFloat32Array(r),a=t[0],n=t[1],l=t[2];for(let e=0;e<r;e+=3)o[e+0]=a,o[e+1]=n,o[e+2]=l;this._state.offsetsBuf.setData(o,s,r)}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,1)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsBatchingRenderers.colorRenderer&&this._pointsBatchingRenderers.colorRenderer.drawLayer(t,this,2)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,5)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,3)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsBatchingRenderers.silhouetteRenderer&&this._pointsBatchingRenderers.silhouetteRenderer.drawLayer(t,this,4)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickMeshRenderer&&this._pointsBatchingRenderers.pickMeshRenderer.drawLayer(t,this,11)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.pickDepthRenderer&&this._pointsBatchingRenderers.pickDepthRenderer.drawLayer(t,this,11)}drawPickNormals(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsBatchingRenderers.occlusionRenderer&&this._pointsBatchingRenderers.occlusionRenderer.drawLayer(t,this,1)}drawShadow(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const Hr=u.vec3();class Wr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter,c=r.pointsMaterial._state;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aColor.bindArrayBuffer(n.colorsBuf);const u=r._sectionPlanesState.sectionPlanes.length;if(u>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*u,o=s.renderFlags;for(let t=0;t<u;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,Hr);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),a.uniform1f(this._uPointSize,c.pointSize);const d="ortho"===r.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,d),l.drawArraysInstancedANGLE(a.POINTS,0,n.positionsBuf.numItems/3,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aColor=i.getAttribute("color"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._aOffset=i.getAttribute("offset"),this._aModelMatrixCol0=i.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=i.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=i.getAttribute("modelMatrixCol2"),this._uOcclusionTexture="uOcclusionTexture",this._uPointSize=i.getLocation("pointSize"),this._uNearPlaneHeight=i.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(e){const t=this._scene,i=t.canvas.gl,s=t.camera.project;if(this._program.bind(),i.uniformMatrix4fv(this._uProjMatrix,!1,s.matrix),t.logarithmicDepthBufferEnabled){const e=2/(Math.log(s.far+1)/Math.LN2);i.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points instancing color vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 modelMatrixCol0;"),s.push("attribute vec4 modelMatrixCol1;"),s.push("attribute vec4 modelMatrixCol2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec4 vColor;"),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition =  positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition  = viewMatrix * worldPosition; "),s.push("vColor = vec4(float(color.r) / 255.0, float(color.g) / 255.0, float(color.b) / 255.0, float(color.a) / 255.0);"),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Points instancing color fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }")),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push("   gl_FragColor = vColor;"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Yr=u.vec3();class qr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter,c=r.pointsMaterial._state;if(!this._program&&(this._allocate(t.model.scene),this.errors))return;if(e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),5===i){const e=r.xrayMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(3===i){const e=r.highlightMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else if(4===i){const e=r.selectedMaterial._state,t=e.fillColor,i=e.fillAlpha;a.uniform4f(this._uColor,t[0],t[1],t[2],i)}else a.uniform4fv(this._uColor,u.vec3([1,1,1]));a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const d=r._sectionPlanesState.sectionPlanes.length;if(d>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*d,o=s.renderFlags;for(let t=0;t<d;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,Yr);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aFlags.bindArrayBuffer(n.flagsBuf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf,a.UNSIGNED_BYTE,!0),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),a.uniform1f(this._uPointSize,c.pointSize);const p="ortho"===r.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,p),l.drawArraysInstancedANGLE(a.POINTS,0,n.positionsBuf.numItems,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uColor=s.getLocation("color"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._uPointSize=s.getLocation("pointSize"),this._uNearPlaneHeight=s.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points instancing silhouette vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("attribute vec4 modelMatrixCol0;"),s.push("attribute vec4 modelMatrixCol1;"),s.push("attribute vec4 modelMatrixCol2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),s.push("uniform vec4 color;"),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("if (int(flags.y) != renderPass) {"),s.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Points instancing silhouette fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("uniform vec4 color;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }")),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = color;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Kr=u.vec3();class Zr{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter,c=r.pointsMaterial._state;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e)),a.uniform1i(this._uRenderPass,i);const u=e.pickViewMatrix||o.viewMatrix,d=h?I(u,h):u;if(a.uniformMatrix4fv(this._uViewMatrix,!1,d),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),r.logarithmicDepthBufferEnabled){const e=2/(Math.log(o.project.far+1)/Math.LN2);a.uniform1f(this._uLogDepthBufFC,e)}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPickColor.bindArrayBuffer(n.pickColorsBuf),l.vertexAttribDivisorANGLE(this._aPickColor.location,1),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),a.uniform1f(this._uPointSize,c.pointSize);const p="ortho"===r.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,p);const _=r._sectionPlanesState.sectionPlanes.length;if(_>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*_,o=s.renderFlags;for(let t=0;t<_;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,Kr);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}l.drawArraysInstancedANGLE(a.POINTS,0,n.positionsBuf.numItems,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aPickColor.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPickInvisible=s.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._uRenderPass=s.getLocation("renderPass"),this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aPickColor=s.getAttribute("pickColor"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._uPointSize=s.getLocation("pointSize"),this._uNearPlaneHeight=s.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(e){const t=this._scene.canvas.gl;this._program.bind(),t.uniform1i(this._uPickInvisible,e.pickInvisible)}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points instancing pick mesh vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("attribute vec4 pickColor;"),s.push("attribute vec4 modelMatrixCol0;"),s.push("attribute vec4 modelMatrixCol1;"),s.push("attribute vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec4 vPickColor;"),s.push("void main(void) {"),s.push("if (int(flags.w) != renderPass) {"),s.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),s.push("  vPickColor = vec4(float(pickColor.r) / 255.0, float(pickColor.g) / 255.0, float(pickColor.b) / 255.0, float(pickColor.a) / 255.0);"),t&&(s.push("  vWorldPosition = worldPosition;"),s.push("  vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Points instancing pick mesh fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vPickColor;"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }")),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("gl_FragColor = vPickColor; "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Qr=u.vec3();class $r{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.canvas.gl,a=t._state,n=this._instanceExt,l=t._state.rtcCenter,h=r.pointsMaterial._state;if(!this._program&&(this._allocate(t),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram());const c=r.camera;o.uniform1i(this._uRenderPass,i),o.uniform1i(this._uPickInvisible,e.pickInvisible);const u=e.pickViewMatrix||c.viewMatrix,d=l?I(u,l):u;if(o.uniformMatrix4fv(this._uViewMatrix,!1,d),o.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),o.uniformMatrix4fv(this._uProjMatrix,!1,e.pickProjMatrix),o.uniform1f(this._uPickZNear,e.pickZNear),o.uniform1f(this._uPickZFar,e.pickZFar),r.logarithmicDepthBufferEnabled){const t=2/(Math.log(e.pickZFar+1)/Math.LN2);o.uniform1f(this._uLogDepthBufFC,t)}const p=r._sectionPlanesState.sectionPlanes.length;if(p>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*p,a=s.renderFlags;for(let t=0;t<p;t++){const s=this._uSectionPlanes[t],r=a.sectionPlanesActivePerLayer[i+t];if(o.uniform1i(s.active,r?1:0),r){const i=e[t];if(l){const e=O(i.dist,i.dir,l,Qr);o.uniform3fv(s.pos,e)}else o.uniform3fv(s.pos,i.pos);o.uniform3fv(s.dir,i.dir)}}}o.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(a.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(a.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(a.modelMatrixCol2Buf),n.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),n.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),n.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(a.positionsBuf),this._aFlags.bindArrayBuffer(a.flagsBuf),n.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(a.flags2Buf),n.vertexAttribDivisorANGLE(this._aFlags2.location,1)),this._aOffset&&(this._aOffset.bindArrayBuffer(a.offsetsBuf),n.vertexAttribDivisorANGLE(this._aOffset.location,1)),o.uniform1f(this._uPointSize,h.pointSize);const _="ortho"===r.camera.projection?1:o.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));o.uniform1f(this._uNearPlaneHeight,_),n.drawArraysInstancedANGLE(o.POINTS,0,a.positionsBuf.numItems,a.numInstances),n.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),n.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),n.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),n.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&n.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&n.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPickInvisible=i.getLocation("pickInvisible"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._aModelMatrixCol0=i.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=i.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=i.getAttribute("modelMatrixCol2"),this._uPickZNear=i.getLocation("pickZNear"),this._uPickZFar=i.getLocation("pickZFar"),this._uPointSize=i.getLocation("pointSize"),this._uNearPlaneHeight=i.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){this._program.bind()}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points instancing pick depth vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("attribute vec4 modelMatrixCol0;"),s.push("attribute vec4 modelMatrixCol1;"),s.push("attribute vec4 modelMatrixCol2;"),s.push("uniform bool pickInvisible;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("varying vec4 vViewPosition;"),s.push("void main(void) {"),s.push("if (int(flags.w) != renderPass) {"),s.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(s.push("  vWorldPosition = worldPosition;"),s.push("  vFlags2 = flags2;")),s.push("  vViewPosition = viewPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Points instancing pick depth fragment shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),s.push("uniform float pickZNear;"),s.push("uniform float pickZFar;"),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec4 vViewPosition;"),s.push("vec4 packDepth(const in float depth) {"),s.push("  const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);"),s.push("  const vec4 bitMask  = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);"),s.push("  vec4 res = fract(depth * bitShift);"),s.push("  res -= res.xxyz * bitMask;"),s.push("  return res;"),s.push("}"),s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }")),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    float zNormalizedDepth = abs((pickZNear + vViewPosition.z) / (pickZFar - pickZNear));"),s.push("    gl_FragColor = packDepth(zNormalizedDepth); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const Jr=u.vec3();class eo{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter,c=r.pointsMaterial._state;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix);const u=r._sectionPlanesState.sectionPlanes.length;if(u>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*u,o=s.renderFlags;for(let t=0;t<u;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,Jr);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aColor&&(this._aColor.bindArrayBuffer(n.colorsBuf),l.vertexAttribDivisorANGLE(this._aColor.location,1)),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),a.uniform1f(this._uPointSize,c.pointSize);const d="ortho"===r.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,d),l.drawArraysInstancedANGLE(a.POINTS,0,n.positionsBuf.numItems,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),this._aColor&&l.vertexAttribDivisorANGLE(this._aColor.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uRenderPass=s.getLocation("renderPass"),this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=s.getLocation("worldMatrix"),this._uViewMatrix=s.getLocation("viewMatrix"),this._uProjMatrix=s.getLocation("projMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._uPointSize=s.getLocation("pointSize"),this._uNearPlaneHeight=s.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=s.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points instancing occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 color;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("attribute vec4 modelMatrixCol0;"),s.push("attribute vec4 modelMatrixCol1;"),s.push("attribute vec4 modelMatrixCol2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push("      gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&s.push("  vWorldPosition = worldPosition;"),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Points instancing occlusion vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("void main(void) {"),e.pointsMaterial.roundPoints&&(s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }")),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0;e<t.sectionPlanes.length;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return s.push("   gl_FragColor = vec4(0.0, 0.0, 1.0, 1.0); "),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const to=u.vec3();class io{constructor(e){this._scene=e,this._hash=this._getHash(),this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()+this._scene.pointsMaterial.hash}drawLayer(e,t,i){const s=t.model,r=s.scene,o=r.camera,a=r.canvas.gl,n=t._state,l=this._instanceExt,h=t._state.rtcCenter,c=r.pointsMaterial._state;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram()),a.uniform1i(this._uRenderPass,i),a.uniformMatrix4fv(this._uWorldMatrix,!1,s.worldMatrix),a.uniformMatrix4fv(this._uViewMatrix,!1,h?I(o.viewMatrix,h):o.viewMatrix);const u=r._sectionPlanesState.sectionPlanes.length;if(u>0){const e=r._sectionPlanesState.sectionPlanes,i=t.layerIndex*u,o=s.renderFlags;for(let t=0;t<u;t++){const s=this._uSectionPlanes[t],r=o.sectionPlanesActivePerLayer[i+t];if(a.uniform1i(s.active,r?1:0),r){const i=e[t];if(h){const e=O(i.dist,i.dir,h,to);a.uniform3fv(s.pos,e)}else a.uniform3fv(s.pos,i.pos);a.uniform3fv(s.dir,i.dir)}}}this._aModelMatrixCol0.bindArrayBuffer(n.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(n.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(n.modelMatrixCol2Buf),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),a.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aPosition.bindArrayBuffer(n.positionsBuf),this._aOffset&&(this._aOffset.bindArrayBuffer(n.offsetsBuf),l.vertexAttribDivisorANGLE(this._aOffset.location,1)),this._aFlags.bindArrayBuffer(n.flagsBuf),l.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(n.flags2Buf),l.vertexAttribDivisorANGLE(this._aFlags2.location,1)),a.uniform1f(this._uPointSize,c.pointSize);const d="ortho"===r.camera.projection?1:a.drawingBufferHeight/(2*Math.tan(.5*r.camera.perspective.fov*Math.PI/180));a.uniform1f(this._uNearPlaneHeight,d),l.drawArraysInstancedANGLE(a.POINTS,0,n.positionsBuf.numItems,n.numInstances),l.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),l.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),l.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&l.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&l.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const i=this._program;this._uRenderPass=i.getLocation("renderPass"),this._uPositionsDecodeMatrix=i.getLocation("positionsDecodeMatrix"),this._uWorldMatrix=i.getLocation("worldMatrix"),this._uViewMatrix=i.getLocation("viewMatrix"),this._uProjMatrix=i.getLocation("projMatrix"),this._uSectionPlanes=[];for(let t=0,s=e._sectionPlanesState.sectionPlanes.length;t<s;t++)this._uSectionPlanes.push({active:i.getLocation("sectionPlaneActive"+t),pos:i.getLocation("sectionPlanePos"+t),dir:i.getLocation("sectionPlaneDir"+t)});this._aPosition=i.getAttribute("position"),this._aOffset=i.getAttribute("offset"),this._aFlags=i.getAttribute("flags"),this._aFlags2=i.getAttribute("flags2"),this._aModelMatrixCol0=i.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=i.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=i.getAttribute("modelMatrixCol2"),this._uPointSize=i.getLocation("pointSize"),this._uNearPlaneHeight=i.getLocation("nearPlaneHeight"),e.logarithmicDepthBufferEnabled&&(this._uLogDepthBufFC=i.getLocation("logDepthBufFC"))}_bindProgram(){const e=this._scene,t=e.canvas.gl,i=e.camera.project;if(this._program.bind(),t.uniformMatrix4fv(this._uProjMatrix,!1,i.matrix),e.logarithmicDepthBufferEnabled){const e=2/(Math.log(i.far+1)/Math.LN2);t.uniform1f(this._uLogDepthBufFC,e)}}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=e.pointsMaterial._state,s=[];return s.push("// Points instancing depth vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("uniform int renderPass;"),s.push("attribute vec3 position;"),e.entityOffsetsEnabled&&s.push("attribute vec3 offset;"),s.push("attribute vec4 flags;"),s.push("attribute vec4 flags2;"),s.push("attribute vec4 modelMatrixCol0;"),s.push("attribute vec4 modelMatrixCol1;"),s.push("attribute vec4 modelMatrixCol2;"),s.push("uniform mat4 worldMatrix;"),s.push("uniform mat4 viewMatrix;"),s.push("uniform mat4 projMatrix;"),s.push("uniform mat4 positionsDecodeMatrix;"),s.push("uniform float pointSize;"),i.perspectivePoints&&s.push("uniform float nearPlaneHeight;"),e.logarithmicDepthBufferEnabled&&(s.push("uniform float logDepthBufFC;"),V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("varying float vFragDepth;")),t&&(s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;")),s.push("void main(void) {"),s.push("if (int(flags.x) != renderPass) {"),s.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),s.push("} else {"),s.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),s.push("  worldPosition = worldMatrix * vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&s.push("      worldPosition.xyz = worldPosition.xyz + offset;"),s.push("  vec4 viewPosition  = viewMatrix * worldPosition; "),t&&(s.push("vWorldPosition = worldPosition;"),s.push("vFlags2 = flags2;")),s.push("vec4 clipPos = projMatrix * viewPosition;"),e.logarithmicDepthBufferEnabled&&(V.SUPPORTED_EXTENSIONS.EXT_frag_depth?s.push("vFragDepth = 1.0 + clipPos.w;"):(s.push("clipPos.z = log2( max( 1e-6, clipPos.w + 1.0 ) ) * logDepthBufFC - 1.0;"),s.push("clipPos.z *= clipPos.w;"))),s.push("gl_Position = clipPos;"),i.perspectivePoints?(s.push("gl_PointSize = (nearPlaneHeight * pointSize) / clipPos.w;"),s.push("gl_PointSize = max(gl_PointSize, "+Math.floor(i.minPerspectivePointSize)+".0);"),s.push("gl_PointSize = min(gl_PointSize, "+Math.floor(i.maxPerspectivePointSize)+".0);")):s.push("gl_PointSize = pointSize;"),s.push("}"),s.push("}"),s}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState;let i,s;const r=t.sectionPlanes.length>0,o=[];if(o.push("// Points instancing depth vertex shader"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("#extension GL_EXT_frag_depth : enable"),o.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),o.push("precision highp float;"),o.push("precision highp int;"),o.push("#else"),o.push("precision mediump float;"),o.push("precision mediump int;"),o.push("#endif"),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(o.push("uniform float logDepthBufFC;"),o.push("varying float vFragDepth;")),r)for(o.push("varying vec4 vWorldPosition;"),o.push("varying vec4 vFlags2;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("uniform bool sectionPlaneActive"+i+";"),o.push("uniform vec3 sectionPlanePos"+i+";"),o.push("uniform vec3 sectionPlaneDir"+i+";");if(o.push("const float   packUpScale = 256. / 255.;"),o.push("const float   unpackDownscale = 255. / 256.;"),o.push("const vec3    packFactors = vec3( 256. * 256. * 256., 256. * 256.,  256. );"),o.push("const vec4    unpackFactors = unpackDownscale / vec4( packFactors, 1. );"),o.push("const float   shiftRight8 = 1.0 / 256.;"),o.push("vec4 packDepthToRGBA( const in float v ) {"),o.push("    vec4 r = vec4( fract( v * packFactors ), v );"),o.push("    r.yzw -= r.xyz * shiftRight8;"),o.push("    return r * packUpScale;"),o.push("}"),o.push("void main(void) {"),e.pointsMaterial.roundPoints&&(o.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),o.push("  float r = dot(cxy, cxy);"),o.push("  if (r > 1.0) {"),o.push("       discard;"),o.push("  }")),r){for(o.push("  bool clippable = (float(vFlags2.x) > 0.0);"),o.push("  if (clippable) {"),o.push("  float dist = 0.0;"),i=0,s=t.sectionPlanes.length;i<s;i++)o.push("if (sectionPlaneActive"+i+") {"),o.push("   dist += clamp(dot(-sectionPlaneDir"+i+".xyz, vWorldPosition.xyz - sectionPlanePos"+i+".xyz), 0.0, 1000.0);"),o.push("}");o.push("if (dist > 0.0) { discard; }"),o.push("}")}return o.push("    gl_FragColor = packDepthToRGBA( gl_FragCoord.z); "),e.logarithmicDepthBufferEnabled&&V.SUPPORTED_EXTENSIONS.EXT_frag_depth&&o.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),o.push("}"),o}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}const so=u.vec3();class ro{constructor(e){this._scene=e,this._hash=this._getHash(),this._lastLightId=null,this._allocate()}getValid(){return this._hash===this._getHash()}_getHash(){return this._scene._sectionPlanesState.getHash()}drawLayer(e,t){const i=t.model,s=i.scene,r=s.canvas.gl,o=t._state,a=this._instanceExt;if(!this._program&&(this._allocate(),this.errors))return;e.lastProgramId!==this._program.id&&(e.lastProgramId=this._program.id,this._bindProgram(e,t)),r.uniformMatrix4fv(this._uPositionsDecodeMatrix,!1,t._state.positionsDecodeMatrix),this._aModelMatrixCol0.bindArrayBuffer(o.modelMatrixCol0Buf),this._aModelMatrixCol1.bindArrayBuffer(o.modelMatrixCol1Buf),this._aModelMatrixCol2.bindArrayBuffer(o.modelMatrixCol2Buf),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,1),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,1),this._aPosition.bindArrayBuffer(o.positionsBuf),this._aOffset&&(this._aOffset.bindArrayBuffer(o.offsetsBuf),a.vertexAttribDivisorANGLE(this._aOffset.location,1)),this._aColor.bindArrayBuffer(o.colorsBuf),a.vertexAttribDivisorANGLE(this._aColor.location,1),this._aFlags.bindArrayBuffer(o.flagsBuf),a.vertexAttribDivisorANGLE(this._aFlags.location,1),this._aFlags2&&(this._aFlags2.bindArrayBuffer(o.flags2Buf),a.vertexAttribDivisorANGLE(this._aFlags2.location,1));const n=s._sectionPlanesState.sectionPlanes.length;if(n>0){const e=s._sectionPlanesState.sectionPlanes,o=t.layerIndex*n,a=i.renderFlags,l=t._state.rtcCenter;for(let t=0;t<n;t++){const i=this._uSectionPlanes[t],s=a.sectionPlanesActivePerLayer[o+t];if(r.uniform1i(i.active,s?1:0),s){const s=e[t];if(l){const e=O(s.dist,s.dir,l,so);r.uniform3fv(i.pos,e)}else r.uniform3fv(i.pos,s.pos);r.uniform3fv(i.dir,s.dir)}}}r.uniform1f(this._uPointSize,10),a.drawArraysInstancedANGLE(r.POINTS,0,o.positionsBuf.numItems,o.numInstances),a.vertexAttribDivisorANGLE(this._aModelMatrixCol0.location,0),a.vertexAttribDivisorANGLE(this._aModelMatrixCol1.location,0),a.vertexAttribDivisorANGLE(this._aModelMatrixCol2.location,0),a.vertexAttribDivisorANGLE(this._aColor.location,0),a.vertexAttribDivisorANGLE(this._aFlags.location,0),this._aFlags2&&a.vertexAttribDivisorANGLE(this._aFlags2.location,0),this._aOffset&&a.vertexAttribDivisorANGLE(this._aOffset.location,0)}_allocate(){const e=this._scene,t=e.canvas.gl,i=e._sectionPlanesState;if(this._program=new J(t,this._buildShader()),this._program.errors)return void(this.errors=this._program.errors);this._instanceExt=t.getExtension("ANGLE_instanced_arrays");const s=this._program;this._uPositionsDecodeMatrix=s.getLocation("positionsDecodeMatrix"),this._uShadowViewMatrix=s.getLocation("shadowViewMatrix"),this._uShadowProjMatrix=s.getLocation("shadowProjMatrix"),this._uSectionPlanes=[];for(let e=0,t=i.sectionPlanes.length;e<t;e++)this._uSectionPlanes.push({active:s.getLocation("sectionPlaneActive"+e),pos:s.getLocation("sectionPlanePos"+e),dir:s.getLocation("sectionPlaneDir"+e)});this._aPosition=s.getAttribute("position"),this._aOffset=s.getAttribute("offset"),this._aColor=s.getAttribute("color"),this._aFlags=s.getAttribute("flags"),this._aFlags2=s.getAttribute("flags2"),this._aModelMatrixCol0=s.getAttribute("modelMatrixCol0"),this._aModelMatrixCol1=s.getAttribute("modelMatrixCol1"),this._aModelMatrixCol2=s.getAttribute("modelMatrixCol2"),this._uPointSize=s.getLocation("pointSize")}_bindProgram(e,t){const i=this._scene.canvas.gl;this._program.bind(),i.uniformMatrix4fv(this._uShadowViewMatrix,!1,e.shadowViewMatrix),i.uniformMatrix4fv(this._uShadowProjMatrix,!1,e.shadowProjMatrix),this._lastLightId=null}_buildShader(){return{vertex:this._buildVertexShader(),fragment:this._buildFragmentShader()}}_buildVertexShader(){const e=this._scene,t=e._sectionPlanesState.sectionPlanes.length>0,i=[];return i.push("// Instancing geometry shadow drawing vertex shader"),i.push("attribute vec3 position;"),e.entityOffsetsEnabled&&i.push("attribute vec3 offset;"),i.push("attribute vec4 color;"),i.push("attribute vec4 flags;"),i.push("attribute vec4 flags2;"),i.push("attribute vec4 modelMatrixCol0;"),i.push("attribute vec4 modelMatrixCol1;"),i.push("attribute vec4 modelMatrixCol2;"),i.push("uniform mat4 shadowViewMatrix;"),i.push("uniform mat4 shadowProjMatrix;"),i.push("uniform mat4 positionsDecodeMatrix;"),i.push("uniform float pointSize;"),t&&(i.push("varying vec4 vWorldPosition;"),i.push("varying vec4 vFlags2;")),i.push("void main(void) {"),i.push("bool visible      = (float(flags.x) > 0.0);"),i.push("bool transparent  = ((float(color.a) / 255.0) < 1.0);"),i.push("if (!visible || transparent) {"),i.push("   gl_Position = vec4(0.0, 0.0, 0.0, 0.0);"),i.push("} else {"),i.push("  vec4 worldPosition = positionsDecodeMatrix * vec4(position, 1.0); "),i.push("  worldPosition = vec4(dot(worldPosition, modelMatrixCol0), dot(worldPosition, modelMatrixCol1), dot(worldPosition, modelMatrixCol2), 1.0);"),e.entityOffsetsEnabled&&i.push("      worldPosition.xyz = worldPosition.xyz + offset;"),i.push("  vec4 viewPosition  = shadowViewMatrix * worldPosition; "),t&&(i.push("vWorldPosition = worldPosition;"),i.push("vFlags2 = flags2;")),i.push("  gl_Position = shadowProjMatrix * viewPosition;"),i.push("}"),i.push("gl_PointSize = pointSize;"),i.push("}"),i}_buildFragmentShader(){const e=this._scene,t=e._sectionPlanesState,i=t.sectionPlanes.length>0,s=[];if(s.push("// Instancing geometry depth drawing fragment shader"),e.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("#extension GL_EXT_frag_depth : enable"),s.push("#ifdef GL_FRAGMENT_PRECISION_HIGH"),s.push("precision highp float;"),s.push("precision highp int;"),s.push("#else"),s.push("precision mediump float;"),s.push("precision mediump int;"),s.push("#endif"),e.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS.EXT_frag_depth&&(s.push("uniform float logDepthBufFC;"),s.push("varying float vFragDepth;")),i){s.push("varying vec4 vWorldPosition;"),s.push("varying vec4 vFlags2;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("uniform bool sectionPlaneActive"+e+";"),s.push("uniform vec3 sectionPlanePos"+e+";"),s.push("uniform vec3 sectionPlaneDir"+e+";")}if(s.push("varying vec3 vViewNormal;"),s.push("vec3 packNormalToRGB( const in vec3 normal ) {"),s.push("    return normalize( normal ) * 0.5 + 0.5;"),s.push("}"),s.push("void main(void) {"),s.push("  vec2 cxy = 2.0 * gl_PointCoord - 1.0;"),s.push("  float r = dot(cxy, cxy);"),s.push("  if (r > 1.0) {"),s.push("       discard;"),s.push("  }"),i){s.push("  bool clippable = (float(vFlags2.x) > 0.0);"),s.push("  if (clippable) {"),s.push("  float dist = 0.0;");for(let e=0,i=t.sectionPlanes.length;e<i;e++)s.push("if (sectionPlaneActive"+e+") {"),s.push("   dist += clamp(dot(-sectionPlaneDir"+e+".xyz, vWorldPosition.xyz - sectionPlanePos"+e+".xyz), 0.0, 1000.0);"),s.push("}");s.push("if (dist > 0.0) { discard; }"),s.push("}")}return e.logarithmicDepthBufferEnabled&&WEBGL_INFO.SUPPORTED_EXTENSIONS.EXT_frag_depth&&s.push("gl_FragDepthEXT = log2( vFragDepth ) * logDepthBufFC * 0.5;"),s.push("    gl_FragColor = vec4(packNormalToRGB(vViewNormal), 1.0); "),s.push("}"),s}webglContextRestored(){this._program=null}destroy(){this._program&&this._program.destroy(),this._program=null}}class oo{constructor(e){this._scene=e}_compile(){this._colorRenderer&&!this._colorRenderer.getValid()&&(this._colorRenderer.destroy(),this._colorRenderer=null),this._depthRenderer&&!this._depthRenderer.getValid()&&(this._depthRenderer.destroy(),this._depthRenderer=null),this._silhouetteRenderer&&!this._silhouetteRenderer.getValid()&&(this._silhouetteRenderer.destroy(),this._silhouetteRenderer=null),this._pickMeshRenderer&&!this._pickMeshRenderer.getValid()&&(this._pickMeshRenderer.destroy(),this._pickMeshRenderer=null),this._pickDepthRenderer&&!this._pickDepthRenderer.getValid()&&(this._pickDepthRenderer.destroy(),this._pickDepthRenderer=null),this._occlusionRenderer&&!1===this._occlusionRenderer.getValid()&&(this._occlusionRenderer.destroy(),this._occlusionRenderer=null),this._shadowRenderer&&!this._shadowRenderer.getValid()&&(this._shadowRenderer.destroy(),this._shadowRenderer=null)}get colorRenderer(){return this._colorRenderer||(this._colorRenderer=new Wr(this._scene,!1)),this._colorRenderer}get silhouetteRenderer(){return this._silhouetteRenderer||(this._silhouetteRenderer=new qr(this._scene)),this._silhouetteRenderer}get depthRenderer(){return this._depthRenderer||(this._depthRenderer=new io(this._scene)),this._depthRenderer}get pickMeshRenderer(){return this._pickMeshRenderer||(this._pickMeshRenderer=new Zr(this._scene)),this._pickMeshRenderer}get pickDepthRenderer(){return this._pickDepthRenderer||(this._pickDepthRenderer=new $r(this._scene)),this._pickDepthRenderer}get occlusionRenderer(){return this._occlusionRenderer||(this._occlusionRenderer=new eo(this._scene)),this._occlusionRenderer}get shadowRenderer(){return this._shadowRenderer||(this._shadowRenderer=new ro(this._scene)),this._shadowRenderer}_destroy(){this._colorRenderer&&this._colorRenderer.destroy(),this._depthRenderer&&this._depthRenderer.destroy(),this._silhouetteRenderer&&this._silhouetteRenderer.destroy(),this._pickMeshRenderer&&this._pickMeshRenderer.destroy(),this._pickDepthRenderer&&this._pickDepthRenderer.destroy(),this._occlusionRenderer&&this._occlusionRenderer.destroy(),this._shadowRenderer&&this._shadowRenderer.destroy()}}const ao={},no=new Uint8Array(4),lo=u.vec4([0,0,0,1]),ho=u.vec4([0,0,0,1]),co=u.vec4([0,0,0,1]),uo=new Float32Array(3);class po{constructor(e,t){this.sortId="PointsInstancingLayer",this.layerIndex=t.layerIndex,this._pointsInstancingRenderers=function(e){const t=e.id;let i=ao[t];return i||(i=new oo(e),ao[t]=i,i._compile(),e.on("compile",(()=>{i._compile()})),e.on("destroyed",(()=>{delete ao[t],i._destroy()}))),i}(e.scene),this.model=e,this._aabb=u.collapseAABB3();const i=e.scene.canvas.gl,s={positionsDecodeMatrix:u.mat4(),numInstances:0,obb:u.OBB3(),rtcCenter:null},r=!!t.positionsDecodeMatrix;if(t.positions)if(r){let e=!1;s.positionsBuf=new ee(i,i.ARRAY_BUFFER,t.positions,t.positions.length,3,i.STATIC_DRAW,e),s.positionsDecodeMatrix.set(t.positionsDecodeMatrix);let r=u.collapseAABB3();u.expandAABB3Points3(r,t.positions),Xe.decompressAABB(r,s.positionsDecodeMatrix),u.AABB3ToOBB3(r,s.obb)}else{let e=t.positions.length,r=u.collapseAABB3();u.expandAABB3Points3(r,t.positions),u.AABB3ToOBB3(r,s.obb);const o=ts(t.positions,r,s.positionsDecodeMatrix);let a=!1;s.positionsBuf=new ee(i,i.ARRAY_BUFFER,o,e,3,i.STATIC_DRAW,a)}if(t.colors){const e=t.colors,r=new Uint8Array(e.length/3*4);for(let t=0,i=0,s=e.length;t<s;t+=3,i+=4)r[t+0]=255*e[i+0],r[i+1]=255*e[t+1],r[i+2]=255*e[t+2],r[i+3]=255;let o=!1;s.colorsBuf=new ee(i,i.ARRAY_BUFFER,r,r.length,4,i.STATIC_DRAW,o)}this._state=new me(s),this._numPortions=0,this._numVisibleLayerPortions=0,this._numTransparentLayerPortions=0,this._numXRayedLayerPortions=0,this._numHighlightedLayerPortions=0,this._numSelectedLayerPortions=0,this._numClippableLayerPortions=0,this._numEdgesLayerPortions=0,this._numPickableLayerPortions=0,this._numCulledLayerPortions=0,this._pickColors=[],this._offsets=[],this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[],this._portions=[],t.rtcCenter&&(this._state.rtcCenter=u.vec3(t.rtcCenter)),this._finalized=!1,this.aabb=u.collapseAABB3()}createPortion(e){const t=e.meshMatrix,i=e.worldMatrix,s=e.aabb,r=e.pickColor;if(this._finalized)throw"Already finalized";this.model.scene.entityOffsetsEnabled&&(this._offsets.push(0),this._offsets.push(0),this._offsets.push(0)),this._modelMatrixCol0.push(t[0]),this._modelMatrixCol0.push(t[4]),this._modelMatrixCol0.push(t[8]),this._modelMatrixCol0.push(t[12]),this._modelMatrixCol1.push(t[1]),this._modelMatrixCol1.push(t[5]),this._modelMatrixCol1.push(t[9]),this._modelMatrixCol1.push(t[13]),this._modelMatrixCol2.push(t[2]),this._modelMatrixCol2.push(t[6]),this._modelMatrixCol2.push(t[10]),this._modelMatrixCol2.push(t[14]),this._pickColors.push(r[0]),this._pickColors.push(r[1]),this._pickColors.push(r[2]),this._pickColors.push(r[3]),u.collapseAABB3(s);const o=this._state.obb,a=o.length;for(let e=0;e<a;e+=4)lo[0]=o[e+0],lo[1]=o[e+1],lo[2]=o[e+2],u.transformPoint4(t,lo,ho),i?(u.transformPoint4(i,ho,co),u.expandAABB3Point3(s,co)):u.expandAABB3Point3(s,ho);if(this._state.rtcCenter){const e=this._state.rtcCenter;s[0]+=e[0],s[1]+=e[1],s[2]+=e[2],s[3]+=e[0],s[4]+=e[1],s[5]+=e[2]}u.expandAABB3(this.aabb,s),this._state.numInstances++;const n=this._portions.length;return this._portions.push({}),this._numPortions++,this.model.numPortions++,n}finalize(){if(this._finalized)throw"Already finalized";const e=this.model.scene.canvas.gl,t=this._pickColors.length;if(t>0){let i=!1,s=!0;this._state.flagsBuf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(t),t,4,e.DYNAMIC_DRAW,i),this._state.flags2Buf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(t),t,4,e.DYNAMIC_DRAW,s)}if(this.model.scene.entityOffsetsEnabled&&this._offsets.length>0){const t=!1;this._state.offsetsBuf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._offsets),this._offsets.length,3,e.DYNAMIC_DRAW,t),this._offsets=[]}if(this._modelMatrixCol0.length>0){const t=!1;this._state.modelMatrixCol0Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol0),this._modelMatrixCol0.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol1Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol1),this._modelMatrixCol1.length,4,e.STATIC_DRAW,t),this._state.modelMatrixCol2Buf=new ee(e,e.ARRAY_BUFFER,new Float32Array(this._modelMatrixCol2),this._modelMatrixCol2.length,4,e.STATIC_DRAW,t),this._modelMatrixCol0=[],this._modelMatrixCol1=[],this._modelMatrixCol2=[]}if(this._pickColors.length>0){const t=!1;this._state.pickColorsBuf=new ee(e,e.ARRAY_BUFFER,new Uint8Array(this._pickColors),this._pickColors.length,4,e.STATIC_DRAW,t),this._pickColors=[]}this._finalized=!0}initFlags(e,t,i){1&t&&(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++),t&D&&(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++),t&S&&(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++),t&L&&(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++),t&C&&(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++),t&B&&(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++),8&t&&(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++),4&t&&(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++),i&&(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++),this._setFlags(e,t,i),this._setFlags2(e,t)}setVisible(e,t,i){if(!this._finalized)throw"Not finalized";1&t?(this._numVisibleLayerPortions++,this.model.numVisibleLayerPortions++):(this._numVisibleLayerPortions--,this.model.numVisibleLayerPortions--),this._setFlags(e,t,i)}setHighlighted(e,t,i){if(!this._finalized)throw"Not finalized";t&D?(this._numHighlightedLayerPortions++,this.model.numHighlightedLayerPortions++):(this._numHighlightedLayerPortions--,this.model.numHighlightedLayerPortions--),this._setFlags(e,t,i)}setXRayed(e,t,i){if(!this._finalized)throw"Not finalized";t&S?(this._numXRayedLayerPortions++,this.model.numXRayedLayerPortions++):(this._numXRayedLayerPortions--,this.model.numXRayedLayerPortions--),this._setFlags(e,t,i)}setSelected(e,t,i){if(!this._finalized)throw"Not finalized";t&L?(this._numSelectedLayerPortions++,this.model.numSelectedLayerPortions++):(this._numSelectedLayerPortions--,this.model.numSelectedLayerPortions--),this._setFlags(e,t,i)}setEdges(e,t,i){if(!this._finalized)throw"Not finalized";t&B?(this._numEdgesLayerPortions++,this.model.numEdgesLayerPortions++):(this._numEdgesLayerPortions--,this.model.numEdgesLayerPortions--),this._setFlags(e,t,i)}setClippable(e,t){if(!this._finalized)throw"Not finalized";t&C?(this._numClippableLayerPortions++,this.model.numClippableLayerPortions++):(this._numClippableLayerPortions--,this.model.numClippableLayerPortions--),this._setFlags2(e,t)}setCollidable(e,t){if(!this._finalized)throw"Not finalized"}setPickable(e,t,i){if(!this._finalized)throw"Not finalized";8&t?(this._numPickableLayerPortions++,this.model.numPickableLayerPortions++):(this._numPickableLayerPortions--,this.model.numPickableLayerPortions--),this._setFlags2(e,t,i)}setCulled(e,t,i){if(!this._finalized)throw"Not finalized";4&t?(this._numCulledLayerPortions++,this.model.numCulledLayerPortions++):(this._numCulledLayerPortions--,this.model.numCulledLayerPortions--),this._setFlags(e,t,i)}setColor(e,t){if(!this._finalized)throw"Not finalized";no[0]=t[0],no[1]=t[1],no[2]=t[2],no[3]=t[3],this._state.colorsBuf.setData(no,4*e,4)}setTransparent(e,t,i){i?(this._numTransparentLayerPortions++,this.model.numTransparentLayerPortions++):(this._numTransparentLayerPortions--,this.model.numTransparentLayerPortions--),this._setFlags(e,t,i)}_setFlags(e,t,i){if(!this._finalized)throw"Not finalized";const s=!!(1&t),r=!!(t&S),o=!!(t&D),a=!!(t&L),n=!!(4&t);let l,h;l=!s||n||r?0:i?2:1,h=!s||n?0:a?4:o?3:r?5:0;let c=0;c=!s||n?0:a?9:o?8:r?10:t&B?i?7:6:0;let u=s&&!n&&8&t?11:0;no[0]=l,no[1]=h,no[2]=c,no[3]=u,this._state.flagsBuf.setData(no,4*e,4)}_setFlags2(e,t){if(!this._finalized)throw"Not finalized";const i=t&C?255:0;no[0]=i,this._state.flags2Buf.setData(no,4*e,4)}setOffset(e,t){if(!this._finalized)throw"Not finalized";this.model.scene.entityOffsetsEnabled?(uo[0]=t[0],uo[1]=t[1],uo[2]=t[2],this._state.offsetsBuf.setData(uo,3*e,3)):this.model.error("Entity#offset not enabled for this Viewer")}drawColorOpaque(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._numTransparentLayerPortions!==this._numPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,1)}drawColorTransparent(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numTransparentLayerPortions&&this._numXRayedLayerPortions!==this._numPortions&&this._pointsInstancingRenderers.colorRenderer&&this._pointsInstancingRenderers.colorRenderer.drawLayer(t,this,2)}drawDepth(e,t){}drawNormals(e,t){}drawSilhouetteXRayed(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numXRayedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,5)}drawSilhouetteHighlighted(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numHighlightedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,3)}drawSilhouetteSelected(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&0!==this._numSelectedLayerPortions&&this._pointsInstancingRenderers.silhouetteRenderer&&this._pointsInstancingRenderers.silhouetteRenderer.drawLayer(t,this,4)}drawEdgesColorOpaque(e,t){}drawEdgesColorTransparent(e,t){}drawEdgesHighlighted(e,t){}drawEdgesSelected(e,t){}drawEdgesXRayed(e,t){}drawOcclusion(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.occlusionRenderer&&this._pointsInstancingRenderers.occlusionRenderer.drawLayer(t,this,1)}drawShadow(e,t){}drawPickMesh(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickMeshRenderer&&this._pointsInstancingRenderers.pickMeshRenderer.drawLayer(t,this,11)}drawPickDepths(e,t){this._numCulledLayerPortions!==this._numPortions&&0!==this._numVisibleLayerPortions&&this._pointsInstancingRenderers.pickDepthRenderer&&this._pointsInstancingRenderers.pickDepthRenderer.drawLayer(t,this,11)}drawPickNormals(e,t){}destroy(){const e=this._state;e.positionsBuf&&(e.positionsBuf.destroy(),e.positionsBuf=null),e.colorsBuf&&(e.colorsBuf.destroy(),e.colorsBuf=null),e.flagsBuf&&(e.flagsBuf.destroy(),e.flagsBuf=null),e.flags2Buf&&(e.flags2Buf.destroy(),e.flags2Buf=null),e.offsetsBuf&&(e.offsetsBuf.destroy(),e.offsetsBuf=null),e.modelMatrixCol0Buf&&(e.modelMatrixCol0Buf.destroy(),e.modelMatrixCol0Buf=null),e.modelMatrixCol1Buf&&(e.modelMatrixCol1Buf.destroy(),e.modelMatrixCol1Buf=null),e.modelMatrixCol2Buf&&(e.modelMatrixCol2Buf.destroy(),e.modelMatrixCol2Buf=null),e.pickColorsBuf&&(e.pickColorsBuf.destroy(),e.pickColorsBuf=null),e.destroy()}}const _o=V.SUPPORTED_EXTENSIONS.ANGLE_instanced_arrays,fo=u.mat4(),go=u.vec3([1,1,1]),mo=u.vec3([0,0,0]),vo=u.vec3([0,0,0]),bo=u.identityQuaternion();class Po extends A{constructor(e,t={}){super(e,t),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this._aabb=u.collapseAABB3(),this._aabbDirty=!1,this._layerList=[],this._nodeList=[],this._lastRTCCenter=null,this._lastDecodeMatrix=null,this._instancingLayers={},this._currentBatchingLayers={},this._scratchMemory=(bi++,vi),this._meshes={},this._nodes={},this.renderFlags=new Yt,this.numGeometries=0,this.numPortions=0,this.numVisibleLayerPortions=0,this.numTransparentLayerPortions=0,this.numXRayedLayerPortions=0,this.numHighlightedLayerPortions=0,this.numSelectedLayerPortions=0,this.numEdgesLayerPortions=0,this.numPickableLayerPortions=0,this.numClippableLayerPortions=0,this.numCulledLayerPortions=0,this.numEntities=0,this._numTriangles=0,this._numLines=0,this._numPoints=0,this._edgeThreshold=t.edgeThreshold||10,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.backfaces=t.backfaces,this._position=new Float32Array(t.position||[0,0,0]),this._rotation=new Float32Array(t.rotation||[0,0,0]),this._quaternion=new Float32Array(t.quaternion||[0,0,0,1]),t.rotation&&u.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._scale=new Float32Array(t.scale||[1,1,1]),this._worldMatrix=u.mat4(),u.composeMat4(this._position,this._quaternion,this._scale,this._worldMatrix),this._worldNormalMatrix=u.mat4(),u.inverseMat4(this._worldMatrix,this._worldNormalMatrix),u.transposeMat4(this._worldNormalMatrix),(t.matrix||t.position||t.rotation||t.scale||t.quaternion)&&(this._viewMatrix=u.mat4(),this._viewNormalMatrix=u.mat4(),this._viewMatrixDirty=!0,this._worldMatrixNonIdentity=!0),this._opacity=1,this._colorize=[1,1,1],this._saoEnabled=!1!==t.saoEnabled,this._pbrEnabled=!!t.pbrEnabled,this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._onCameraViewMatrix=this.scene.camera.on("matrix",(()=>{this._viewMatrixDirty=!0}))}get isPerformanceModel(){return!0}get position(){return this._position}get rotation(){return this._rotation}get quaternion(){return this._quaternion}get scale(){return this._scale}get matrix(){return this._worldMatrix}get worldMatrix(){return this._worldMatrix}get worldNormalMatrix(){return this._worldNormalMatrix}get viewMatrix(){return this._viewMatrix?(this._viewMatrixDirty&&(u.mulMat4(this.scene.camera.viewMatrix,this._worldMatrix,this._viewMatrix),u.inverseMat4(this._viewMatrix,this._viewNormalMatrix),u.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewMatrix):this.scene.camera.viewMatrix}getPickViewMatrix(e){return this._viewMatrix?this._viewMatrix:e}get viewNormalMatrix(){return this._viewNormalMatrix?(this._viewMatrixDirty&&(u.mulMat4(this.scene.camera.viewMatrix,this._worldMatrix,this._viewMatrix),u.inverseMat4(this._viewMatrix,this._viewNormalMatrix),u.transposeMat4(this._viewNormalMatrix),this._viewMatrixDirty=!1),this._viewNormalMatrix):this.scene.camera.viewNormalMatrix}createGeometry(e){if(!_o)return void this.error("WebGL instanced arrays not supported");const t=e.id;if(null==t)return void this.error("Config missing: id");if(this._instancingLayers[t])return void this.error("Geometry already created: "+t);let i;const s=e.primitive;if(null!=s){switch(s){case"triangles":case"solid":i=new Ks(this,f.apply({layerIndex:0,solid:!0},e)),this._numTriangles+=e.indices?Math.round(e.indices.length/3):0;break;case"surface":i=new Ks(this,f.apply({layerIndex:0,solid:!1},e)),this._numTriangles+=e.indices?Math.round(e.indices.length/3):0;break;case"lines":i=new Mr(this,f.apply({layerIndex:0},e)),this._numLines+=e.indices?Math.round(e.indices.length/2):0;break;case"points":i=new po(this,f.apply({layerIndex:0},e)),this._numPoints+=e.positions?Math.round(e.positions.length/3):0}this._instancingLayers[t]=i,this._layerList.push(i),this.numGeometries++}else this.error("Config missing: primitive")}createMesh(e){let t=e.id;if(null==t)return void this.error("Config missing: id");if(this._meshes[t])return void this.error("PerformanceModel already has a Mesh with this ID: "+t);const i=e.geometryId,s=void 0!==i;if(s){if(!_o)return void this.error("WebGL instanced arrays not supported");if(!this._instancingLayers[i])return void this.error("Geometry not found: "+i+" - ensure that you create it first with createGeometry()")}let r,o;const a=e.color?new Uint8Array([Math.floor(255*e.color[0]),Math.floor(255*e.color[1]),Math.floor(255*e.color[2])]):[255,255,255],n=void 0!==e.opacity&&null!==e.opacity?Math.floor(255*e.opacity):255,l=void 0!==e.metallic&&null!==e.metallic?Math.floor(255*e.metallic):0,h=void 0!==e.roughness&&null!==e.roughness?Math.floor(255*e.roughness):255,c=new mi(this,t,a,n),d=c.pickId,p=new Uint8Array([255&d,d>>8&255,d>>16&255,d>>24&255]),_=u.collapseAABB3();if(s){let t,s=this._worldMatrixNonIdentity?this._worldMatrix:null;if(e.matrix)t=e.matrix;else{const i=e.scale||go,s=e.position||mo,r=e.rotation||vo;u.eulerToQuaternion(r,"XYZ",bo),t=u.composeMat4(s,bo,i,fo)}const d=this._instancingLayers[i];r=d,o=d.createPortion({color:a,metallic:l,roughness:h,opacity:n,meshMatrix:t,worldMatrix:s,aabb:_,pickColor:p}),u.expandAABB3(this._aabb,_);const f=Math.round(d.numIndices/3);this._numTriangles+=f,c.numTriangles=f,c.rtcCenter=d.rtcCenter}else{let t=e.primitive||"triangles";"points"!==t&&"lines"!==t&&"triangles"!==t&&"solid"!==t&&"surface"!==t&&(this.error(`Unsupported value for 'primitive': '${t}' - supported values are 'points', 'lines', 'triangles', 'solid' and 'surface'. Defaulting to 'triangles'.`),t="triangles");let i=e.positions;if(!i)return this.error("Config missing: positions (no meshIds provided, so expecting geometry arrays instead)"),null;let s=e.indices,d=e.edgeIndices;if(!e.indices&&"triangles"===t)return this.error("Config missing for triangles primitive: indices (no meshIds provided, so expecting geometry arrays instead)"),null;let f=!1;if(e.rtcCenter&&(this._lastRTCCenter?u.compareVec3(this._lastRTCCenter,e.rtcCenter)||(f=!0,this._lastRTCCenter.set(e.rtcCenter)):(f=!0,this._lastRTCCenter=u.vec3(e.rtcCenter))),e.positionsDecodeMatrix&&(this._lastDecodeMatrix?u.compareMat4(this._lastDecodeMatrix,e.positionsDecodeMatrix)||(f=!0,this._lastDecodeMatrix.set(e.positionsDecodeMatrix)):(f=!0,this._lastDecodeMatrix=u.mat4(e.positionsDecodeMatrix))),f){for(let e in this._currentBatchingLayers)this._currentBatchingLayers.hasOwnProperty(e)&&this._currentBatchingLayers[e].finalize();this._currentBatchingLayers={}}const g=this._worldMatrixNonIdentity?this._worldMatrix:null;let m;if(!e.positionsDecodeMatrix)if(e.matrix)m=e.matrix;else{const t=e.scale||go,i=e.position||mo,s=e.rotation||vo;u.eulerToQuaternion(s,"XYZ",bo),m=u.composeMat4(i,bo,t,fo)}switch(r=this._currentBatchingLayers[t],t){case"triangles":case"solid":case"surface":r&&(r.canCreatePortion(i.length,s.length)||(r.finalize(),delete this._currentBatchingLayers[t],r=null)),r||(r=new ds(this,{layerIndex:0,scratchMemory:this._scratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,rtcCenter:e.rtcCenter,maxGeometryBatchSize:this._maxGeometryBatchSize,solid:"solid"===t}),this._layerList.push(r),this._currentBatchingLayers[t]=r),d||(d=je(i,s,null,this._edgeThreshold)),o=r.createPortion({positions:i,normals:e.normals,indices:s,edgeIndices:d,color:a,metallic:l,roughness:h,colors:e.colors,opacity:n,meshMatrix:m,worldMatrix:g,worldAABB:_,pickColor:p});const u=Math.round(s.length/3);this._numTriangles+=u,c.numTriangles=u;break;case"lines":r&&(r.canCreatePortion(i.length,s.length)||(r.finalize(),delete this._currentBatchingLayers[t],r=null)),r||(r=new hr(this,{layerIndex:0,scratchMemory:this._scratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,rtcCenter:e.rtcCenter,maxGeometryBatchSize:this._maxGeometryBatchSize}),this._layerList.push(r),this._currentBatchingLayers[t]=r),o=r.createPortion({positions:i,indices:s,color:a,colors:e.colors,opacity:n,meshMatrix:m,worldMatrix:g,worldAABB:_,pickColor:p}),this._numLines+=Math.round(s.length/2);break;case"points":r&&(r.canCreatePortion(i.length)||(r.finalize(),delete this._currentBatchingLayers[t],r=null)),r||(r=new Xr(this,{layerIndex:0,scratchMemory:this._scratchMemory,positionsDecodeMatrix:e.positionsDecodeMatrix,rtcCenter:e.rtcCenter,maxGeometryBatchSize:this._maxGeometryBatchSize}),this._layerList.push(r),this._currentBatchingLayers[t]=r),o=r.createPortion({positions:i,color:a,colors:e.colors,opacity:n,meshMatrix:m,worldMatrix:g,worldAABB:_,pickColor:p}),this._numPoints+=Math.round(i.length/3)}u.expandAABB3(this._aabb,_),this.numGeometries++,c.rtcCenter=e.rtcCenter}c.parent=null,c._layer=r,c._portionId=o,c.aabb=_,this._meshes[t]=c}createEntity(e){let t=e.id;void 0===t?t=u.createUUID():this.scene.components[t]&&(this.error("Scene already has a Component with this ID: "+t+" - will assign random ID"),t=u.createUUID());const i=e.meshIds;if(void 0===i)return void this.error("Config missing: meshIds");let s=[];for(let e=0,t=i.length;e<t;e++){const t=i[e],r=this._meshes[t];r?r.parent?this.error("Mesh with ID "+t+" already belongs to object with ID "+r.parent.id+" - ignoring this mesh"):s.push(r):this.error("Mesh with this ID not found: "+t+" - ignoring this mesh")}let r,o=0;if(this._visible&&!1!==e.visible&&(o|=1),this._pickable&&!1!==e.pickable&&(o|=8),this._culled&&!1!==e.culled&&(o|=4),this._clippable&&!1!==e.clippable&&(o|=C),this._collidable&&!1!==e.collidable&&(o|=32),this._edges&&!1!==e.edges&&(o|=B),this._xrayed&&!1!==e.xrayed&&(o|=S),this._highlighted&&!1!==e.highlighted&&(o|=D),this._selected&&!1!==e.selected&&(o|=L),1===s.length)r=s[0].aabb;else{r=u.collapseAABB3();for(let e=0,t=s.length;e<t;e++)u.expandAABB3(r,s[e].aabb)}const a=new F(this,e.isObject,t,s,o,r);return this._nodeList.push(a),this._nodes[t]=a,this.numEntities++,a}finalize(){if(!this.destroyed){for(const e in this._instancingLayers)this._instancingLayers.hasOwnProperty(e)&&this._instancingLayers[e].finalize();for(let e in this._currentBatchingLayers)this._currentBatchingLayers.hasOwnProperty(e)&&this._currentBatchingLayers[e].finalize();this._currentBatchingLayers={};for(let e=0,t=this._nodeList.length;e<t;e++)this._nodeList[e]._finalize();this._layerList.sort(((e,t)=>e.sortId<t.sortId?-1:e.sortId>t.sortId?1:0));for(let e=0,t=this._layerList.length;e<t;e++)this._layerList[e].layerIndex=e;this.glRedraw(),this.scene._aabbDirty=!0}}set backfaces(e){e=!!e,this._backfaces=e,this.glRedraw()}get backfaces(){return this._backfaces}get entityList(){return this._nodeList}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return!1}get aabb(){return this._aabbDirty&&this._rebuildAABB(),this._aabb}_rebuildAABB(){u.collapseAABB3(this._aabb);for(let e=0,t=this._nodeList.length;e<t;e++){const t=this._nodeList[e];u.expandAABB3(this._aabb,t.aabb)}this._aabbDirty=!1}get numTriangles(){return this._numTriangles}get numLines(){return this._numLines}get numPoints(){return this._numPoints}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].visible=e;this.glRedraw()}get visible(){return this.numVisibleLayerPortions>0}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].xrayed=e;this.glRedraw()}get xrayed(){return this.numXRayedLayerPortions>0}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].highlighted=e;this.glRedraw()}get highlighted(){return this.numHighlightedLayerPortions>0}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].selected=e;this.glRedraw()}get selected(){return this.numSelectedLayerPortions>0}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].edges=e;this.glRedraw()}get edges(){return this.numEdgesLayerPortions>0}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].culled=e;this.glRedraw()}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].clippable=e;this.glRedraw()}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].pickable=e}get pickable(){return this.numPickableLayerPortions>0}set colorize(e){this._colorize=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].colorize=e}get colorize(){return this._colorize}set opacity(e){this._opacity=e;for(let t=0,i=this._nodeList.length;t<i;t++)this._nodeList[t].opacity=e}get opacity(){return this._opacity}set castsShadow(e){(e=!1!==e)!==this._castsShadow&&(this._castsShadow=e,this.glRedraw())}get castsShadow(){return this._castsShadow}set receivesShadow(e){(e=!1!==e)!==this._receivesShadow&&(this._receivesShadow=e,this.glRedraw())}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return this._saoEnabled}get pbrEnabled(){return this._pbrEnabled}get isDrawable(){return!0}get isStateSortable(){return!1}stateSortCompare(e,t){}rebuildRenderFlags(){this.renderFlags.reset(),this._updateRenderFlagsVisibleLayers(),this.renderFlags.numLayers>0&&0===this.renderFlags.numVisibleLayers?this.renderFlags.culled=!0:this._updateRenderFlags()}_updateRenderFlagsVisibleLayers(){const e=this.renderFlags;e.numLayers=this._layerList.length,e.numVisibleLayers=0;for(let t=0,i=this._layerList.length;t<i;t++){const i=this._layerList[t];this._getActiveSectionPlanesForLayer(i)&&(e.visibleLayers[e.numVisibleLayers++]=t)}}_getActiveSectionPlanesForLayer(e){const t=this.renderFlags,i=this.scene._sectionPlanesState.sectionPlanes,s=i.length,r=e.layerIndex*s;if(s>0)for(let e=0;e<s;e++)i[e].active?(t.sectionPlanesActivePerLayer[r+e]=!0,t.sectioned=!0):t.sectionPlanesActivePerLayer[r+e]=!1;return!0}_updateRenderFlags(){if(0===this.numVisibleLayerPortions)return;if(this.numCulledLayerPortions===this.numPortions)return;const e=this.renderFlags;if(e.colorOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.colorTransparent=!0),this.numXRayedLayerPortions>0){const t=this.scene.xrayMaterial._state;t.fill&&(t.fillAlpha<1?e.xrayedSilhouetteTransparent=!0:e.xrayedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.xrayedEdgesTransparent=!0:e.xrayedEdgesOpaque=!0)}if(this.numEdgesLayerPortions>0&&this.scene.edgeMaterial._state.edges&&(e.edgesOpaque=this.numTransparentLayerPortions<this.numPortions,this.numTransparentLayerPortions>0&&(e.edgesTransparent=!0)),this.numSelectedLayerPortions>0){const t=this.scene.selectedMaterial._state;t.fill&&(t.fillAlpha<1?e.selectedSilhouetteTransparent=!0:e.selectedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.selectedEdgesTransparent=!0:e.selectedEdgesOpaque=!0)}if(this.numHighlightedLayerPortions>0){const t=this.scene.highlightMaterial._state;t.fill&&(t.fillAlpha<1?e.highlightedSilhouetteTransparent=!0:e.highlightedSilhouetteOpaque=!0),t.edges&&(t.edgeAlpha<1?e.highlightedEdgesTransparent=!0:e.highlightedEdgesOpaque=!0)}}get xrayMaterial(){return this.scene.xrayMaterial}get highlightMaterial(){return this.scene.highlightMaterial}get selectedMaterial(){return this.scene.selectedMaterial}get edgeMaterial(){return this.scene.edgeMaterial}drawColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawColorOpaque(t,e)}}drawColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawColorTransparent(t,e)}}drawDepth(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawDepth(t,e)}}drawNormals(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawNormals(t,e)}}drawSilhouetteXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawSilhouetteXRayed(t,e)}}drawSilhouetteHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawSilhouetteHighlighted(t,e)}}drawSilhouetteSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawSilhouetteSelected(t,e)}}drawEdgesColorOpaque(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawEdgesColorOpaque(t,e)}}drawEdgesColorTransparent(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawEdgesColorTransparent(t,e)}}drawEdgesXRayed(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawEdgesXRayed(t,e)}}drawEdgesHighlighted(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawEdgesHighlighted(t,e)}}drawEdgesSelected(e){const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawEdgesSelected(t,e)}}drawOcclusion(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawOcclusion(t,e)}}drawShadow(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawShadow(t,e)}}drawPickMesh(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawPickMesh(t,e)}}drawPickDepths(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawPickDepths(t,e)}}drawPickNormals(e){if(0===this.numVisibleLayerPortions)return;const t=this.renderFlags;for(let i=0,s=t.visibleLayers.length;i<s;i++){const s=t.visibleLayers[i];this._layerList[s].drawPickNormals(t,e)}}destroy(){for(let e in this._currentBatchingLayers)this._currentBatchingLayers.hasOwnProperty(e)&&this._currentBatchingLayers[e].destroy();this._currentBatchingLayers={},this.scene.camera.off(this._onCameraViewMatrix);for(let e=0,t=this._layerList.length;e<t;e++)this._layerList[e].destroy();for(let e=0,t=this._nodeList.length;e<t;e++)this._nodeList[e]._destroy();this.scene._aabbDirty=!0,this._isModel&&this.scene._deregisterModel(this),0!==bi&&(bi--,0===bi&&vi._clear()),super.destroy()}}const yo=u.vec4(4),Mo=u.vec4(),xo=u.vec4(),wo=u.vec3([1,0,0]),Eo=u.vec3([0,1,0]),Ao=u.vec3([0,0,1]),Co=u.vec3(3),So=u.vec3(3),Do=u.identityMat4();class Lo extends A{constructor(e,t={}){if(super(e,t),this._parentNode=null,this._children=[],this._aabb=null,this._aabbDirty=!0,this.scene._aabbDirty=!0,this._numTriangles=0,this._scale=u.vec3(),this._quaternion=u.identityQuaternion(),this._rotation=u.vec3(),this._position=u.vec3(),this._offset=u.vec3(),this._localMatrix=u.identityMat4(),this._worldMatrix=u.identityMat4(),this._localMatrixDirty=!0,this._worldMatrixDirty=!0,t.matrix?this.matrix=t.matrix:(this.scale=t.scale,this.position=t.position,t.quaternion||(this.rotation=t.rotation)),this._isModel=t.isModel,this._isModel&&this.scene._registerModel(this),this._isObject=t.isObject,this._isObject&&this.scene._registerObject(this),this.rtcCenter=t.rtcCenter,this.visible=t.visible,this.culled=t.culled,this.pickable=t.pickable,this.clippable=t.clippable,this.collidable=t.collidable,this.castsShadow=t.castsShadow,this.receivesShadow=t.receivesShadow,this.xrayed=t.xrayed,this.highlighted=t.highlighted,this.selected=t.selected,this.edges=t.edges,this.colorize=t.colorize,this.opacity=t.opacity,this.offset=t.offset,t.children){const e=t.children;for(let i=0,s=e.length;i<s;i++)this.addChild(e[i],t.inheritStates)}if(t.parentId){const e=this.scene.components[t.parentId];e?e.isNode?e.addChild(this):this.error("Parent is not a Node: '"+t.parentId+"'"):this.error("Parent not found: '"+t.parentId+"'")}else t.parent&&(t.parent.isNode||this.error("Parent is not a Node"),t.parent.addChild(this))}get isEntity(){return!0}get isModel(){return this._isModel}get isObject(){return this._isObject}get aabb(){return this._aabbDirty&&this._updateAABB(),this._aabb}set rtcCenter(e){e?(this._rtcCenter||(this._rtcCenter=u.vec3()),this._rtcCenter.set(e)):this._rtcCenter&&(this._rtcCenter=null);for(let t=0,i=this._children.length;t<i;t++)this._children[t].rtcCenter=e}get rtcCenter(){return this._rtcCenter}get numTriangles(){return this._numTriangles}set visible(e){e=!1!==e,this._visible=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].visible=e;this._isObject&&this.scene._objectVisibilityUpdated(this,e)}get visible(){return this._visible}set xrayed(e){e=!!e,this._xrayed=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].xrayed=e;this._isObject&&this.scene._objectXRayedUpdated(this,e)}get xrayed(){return this._xrayed}set highlighted(e){e=!!e,this._highlighted=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].highlighted=e;this._isObject&&this.scene._objectHighlightedUpdated(this,e)}get highlighted(){return this._highlighted}set selected(e){e=!!e,this._selected=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].selected=e;this._isObject&&this.scene._objectSelectedUpdated(this,e)}get selected(){return this._selected}set edges(e){e=!!e,this._edges=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].edges=e}get edges(){return this._edges}set culled(e){e=!!e,this._culled=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].culled=e}get culled(){return this._culled}set clippable(e){e=!1!==e,this._clippable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].clippable=e}get clippable(){return this._clippable}set collidable(e){e=!1!==e,this._collidable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].collidable=e}get collidable(){return this._collidable}set pickable(e){e=!1!==e,this._pickable=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].pickable=e}get pickable(){return this._pickable}set colorize(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[3]=1),e?(t[0]=e[0],t[1]=e[1],t[2]=e[2]):(t[0]=1,t[1]=1,t[2]=1);for(let e=0,i=this._children.length;e<i;e++)this._children[e].colorize=t;if(this._isObject){const t=!!e;this.scene._objectColorizeUpdated(this,t)}}get colorize(){return this._colorize.slice(0,3)}set opacity(e){let t=this._colorize;t||(t=this._colorize=new Float32Array(4),t[0]=1,t[1]=1,t[2]=1),t[3]=null!=e?e:1;for(let t=0,i=this._children.length;t<i;t++)this._children[t].opacity=e;if(this._isObject){const t=null!=e;this.scene._objectOpacityUpdated(this,t)}}get opacity(){return this._colorize[3]}set castsShadow(e){e=!!e,this._castsShadow=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].castsShadow=e}get castsShadow(){return this._castsShadow}set receivesShadow(e){e=!!e,this._receivesShadow=e;for(let t=0,i=this._children.length;t<i;t++)this._children[t].receivesShadow=e}get receivesShadow(){return this._receivesShadow}get saoEnabled(){return!1}set offset(e){e?(this._offset[0]=e[0],this._offset[1]=e[1],this._offset[2]=e[2]):(this._offset[0]=0,this._offset[1]=0,this._offset[2]=0);for(let e=0,t=this._children.length;e<t;e++)this._children[e].offset=this._offset;this._isObject&&this.scene._objectOffsetUpdated(this,e)}get offset(){return this._offset}get isNode(){return!0}_setLocalMatrixDirty(){this._localMatrixDirty=!0,this._setWorldMatrixDirty()}_setWorldMatrixDirty(){this._worldMatrixDirty=!0;for(let e=0,t=this._children.length;e<t;e++)this._children[e]._setWorldMatrixDirty()}_buildWorldMatrix(){const e=this.matrix;if(this._parentNode)u.mulMat4(this._parentNode.worldMatrix,e,this._worldMatrix);else for(let t=0,i=e.length;t<i;t++)this._worldMatrix[t]=e[t];this._worldMatrixDirty=!1}_setSubtreeAABBsDirty(e){if(e._aabbDirty=!0,e._children)for(let t=0,i=e._children.length;t<i;t++)this._setSubtreeAABBsDirty(e._children[t])}_setAABBDirty(){if(this._setSubtreeAABBsDirty(this),this.collidable)for(let e=this;e;e=e._parentNode)e._aabbDirty=!0}_updateAABB(){if(this.scene._aabbDirty=!0,this._aabb||(this._aabb=u.AABB3()),this._buildAABB)this._buildAABB(this.worldMatrix,this._aabb);else{let e;u.collapseAABB3(this._aabb);for(let t=0,i=this._children.length;t<i;t++)e=this._children[t],e.collidable&&u.expandAABB3(this._aabb,e.aabb)}this._aabbDirty=!1}addChild(e,t){if(f.isNumeric(e)||f.isString(e)){const t=e;if(!(e=this.scene.component[t]))return void this.warn("Component not found: "+f.inQuotes(t));if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+t)}else{if(!e.isNode&&!e.isMesh)return void this.error("Not a Node or Mesh: "+e.id);if(e._parentNode){if(e._parentNode.id===this.id)return void this.warn("Already a child: "+e.id);e._parentNode.removeChild(e)}}if(e.id,e.scene.id===this.scene.id)return this._children.push(e),e._parentNode=this,t&&(e.visible=this.visible,e.culled=this.culled,e.xrayed=this.xrayed,e.highlited=this.highlighted,e.selected=this.selected,e.edges=this.edges,e.clippable=this.clippable,e.pickable=this.pickable,e.collidable=this.collidable,e.castsShadow=this.castsShadow,e.receivesShadow=this.receivesShadow,e.colorize=this.colorize,e.opacity=this.opacity,e.offset=this.offset),e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles+=e.numTriangles,e;this.error("Child not in same Scene: "+e.id)}removeChild(e){for(let t=0,i=this._children.length;t<i;t++)if(this._children[t].id===e.id)return e._parentNode=null,this._children=this._children.splice(t,1),e._setWorldMatrixDirty(),e._setAABBDirty(),this._setAABBDirty(),void(this._numTriangles-=e.numTriangles)}removeChildren(){let e;for(let t=0,i=this._children.length;t<i;t++)e=this._children[t],e._parentNode=null,e._setWorldMatrixDirty(),e._setAABBDirty(),this._numTriangles-=e.numTriangles;this._children=[],this._setAABBDirty()}get numChildren(){return this._children.length}get children(){return this._children}set parent(e){if(f.isNumeric(e)||f.isString(e)){const t=e;if(!(e=this.scene.components[t]))return void this.warn("Node not found: "+f.inQuotes(t));if(!e.isNode)return void this.error("Not a Node: "+e.id)}e.scene.id===this.scene.id?this._parentNode&&this._parentNode.id===e.id?this.warn("Already a child of Node: "+e.id):e.addChild(this):this.error("Node not in same Scene: "+e.id)}get parent(){return this._parentNode}set position(e){this._position.set(e||[0,0,0]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get position(){return this._position}set rotation(e){this._rotation.set(e||[0,0,0]),u.eulerToQuaternion(this._rotation,"XYZ",this._quaternion),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get rotation(){return this._rotation}set quaternion(e){this._quaternion.set(e||[0,0,0,1]),u.quaternionToEuler(this._quaternion,"XYZ",this._rotation),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get quaternion(){return this._quaternion}set scale(e){this._scale.set(e||[1,1,1]),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get scale(){return this._scale}set matrix(e){this._localMatrix||(this._localMatrix=u.identityMat4()),this._localMatrix.set(e||Do),u.decomposeMat4(this._localMatrix,this._position,this._quaternion,this._scale),this._localMatrixDirty=!1,this._setWorldMatrixDirty(),this._setAABBDirty(),this.glRedraw()}get matrix(){return this._localMatrixDirty&&(this._localMatrix||(this._localMatrix=u.identityMat4()),u.composeMat4(this._position,this._quaternion,this._scale,this._localMatrix),this._localMatrixDirty=!1),this._localMatrix}get worldMatrix(){return this._worldMatrixDirty&&this._buildWorldMatrix(),this._worldMatrix}rotate(e,t){return yo[0]=e[0],yo[1]=e[1],yo[2]=e[2],yo[3]=t*u.DEGTORAD,u.angleAxisToQuaternion(yo,Mo),u.mulQuaternions(this.quaternion,Mo,xo),this.quaternion=xo,this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}rotateOnWorldAxis(e,t){return yo[0]=e[0],yo[1]=e[1],yo[2]=e[2],yo[3]=t*u.DEGTORAD,u.angleAxisToQuaternion(yo,Mo),u.mulQuaternions(Mo,this.quaternion,Mo),this}rotateX(e){return this.rotate(wo,e)}rotateY(e){return this.rotate(Eo,e)}rotateZ(e){return this.rotate(Ao,e)}translate(e,t){return u.vec3ApplyQuaternion(this.quaternion,e,Co),u.mulVec3Scalar(Co,t,So),u.addVec3(this.position,So,this.position),this._setLocalMatrixDirty(),this._setAABBDirty(),this.glRedraw(),this}translateX(e){return this.translate(wo,e)}translateY(e){return this.translate(Eo,e)}translateZ(e){return this.translate(Ao,e)}get type(){return"Node"}destroy(){if(super.destroy(),this._parentNode&&this._parentNode.removeChild(this),this._isObject&&(this.scene._deregisterObject(this),this._visible&&this.scene._objectVisibilityUpdated(this,!1),this._xrayed&&this.scene._objectXRayedUpdated(this,!1),this._selected&&this.scene._objectSelectedUpdated(this,!1),this._highlighted&&this.scene._objectHighlightedUpdated(this,!1),this.scene._objectColorizeUpdated(this,!1),this.scene._objectOpacityUpdated(this,!1),this.scene._objectOffsetUpdated(this,!1)),this._isModel&&this.scene._deregisterModel(this),this._children.length){const e=this._children.splice();let t;for(let i=0,s=e.length;i<s;i++)t=e[i],t.destroy()}this._children=[],this._setAABBDirty(),this.scene._aabbDirty=!0}}u.AABB3();const Bo={funcAdd:"FUNC_ADD",funcSubtract:"FUNC_SUBTRACT",funcReverseSubtract:"FUNC_REVERSE_SUBTRACT",zero:"ZERO",one:"ONE",srcColor:"SRC_COLOR",oneMinusSrcColor:"ONE_MINUS_SRC_COLOR",dstColor:"DST_COLOR",oneMinusDstColor:"ONE_MINUS_DST_COLOR",srcAlpha:"SRC_ALPHA",oneMinusSrcAlpha:"ONE_MINUS_SRC_ALPHA",dstAlpha:"DST_ALPHA",oneMinusDstAlpha:"ONE_MINUS_DST_ALPHA",contantColor:"CONSTANT_COLOR",oneMinusConstantColor:"ONE_MINUS_CONSTANT_COLOR",constantAlpha:"CONSTANT_ALPHA",oneMinusConstantAlpha:"ONE_MINUS_CONSTANT_ALPHA",srcAlphaSaturate:"SRC_ALPHA_SATURATE",front:"FRONT",back:"BACK",frontAndBack:"FRONT_AND_BACK",never:"NEVER",less:"LESS",equal:"EQUAL",lequal:"LEQUAL",greater:"GREATER",notequal:"NOTEQUAL",gequal:"GEQUAL",always:"ALWAYS",cw:"CW",ccw:"CCW",linear:"LINEAR",nearest:"NEAREST",linearMipmapNearest:"LINEAR_MIPMAP_NEAREST",nearestMipmapNearest:"NEAREST_MIPMAP_NEAREST",nearestMipmapLinear:"NEAREST_MIPMAP_LINEAR",linearMipmapLinear:"LINEAR_MIPMAP_LINEAR",repeat:"REPEAT",clampToEdge:"CLAMP_TO_EDGE",mirroredRepeat:"MIRRORED_REPEAT",alpha:"ALPHA",rgb:"RGB",rgba:"RGBA",luminance:"LUMINANCE",luminanceAlpha:"LUMINANCE_ALPHA",textureBinding2D:"TEXTURE_BINDING_2D",textureBindingCubeMap:"TEXTURE_BINDING_CUBE_MAP",compareRToTexture:"COMPARE_R_TO_TEXTURE",unsignedByte:"UNSIGNED_BYTE"};function To(e,t,i){if(void 0===t)return i;const s=Bo[t];return void 0===s?i:e[s]}const Ro=new Uint8Array([0,0,0,1]);class Fo{constructor(e,t){this.gl=e,this.target=t||e.TEXTURE_2D,this.texture=e.createTexture(),this.setPreloadColor([0,0,0,0]),this.allocated=!0}setPreloadColor(e){e?(Ro[0]=Math.floor(255*e[0]),Ro[1]=Math.floor(255*e[1]),Ro[2]=Math.floor(255*e[2]),Ro[3]=Math.floor(255*(void 0!==e[3]?e[3]:1))):(Ro[0]=0,Ro[1]=0,Ro[2]=0,Ro[3]=255);const t=this.gl;if(t.bindTexture(this.target,this.texture),t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,t.NEAREST),t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,t.NEAREST),this.target===t.TEXTURE_CUBE_MAP){const e=[t.TEXTURE_CUBE_MAP_POSITIVE_X,t.TEXTURE_CUBE_MAP_NEGATIVE_X,t.TEXTURE_CUBE_MAP_POSITIVE_Y,t.TEXTURE_CUBE_MAP_NEGATIVE_Y,t.TEXTURE_CUBE_MAP_POSITIVE_Z,t.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let i=0,s=e.length;i<s;i++)t.texImage2D(e[i],0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Ro)}else t.texImage2D(this.target,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,Ro);t.bindTexture(this.target,null)}setTarget(e){this.target=e||this.gl.TEXTURE_2D}setImage(e,t){const i=this.gl;if(i.bindTexture(this.target,this.texture),i.pixelStorei(i.UNPACK_FLIP_Y_WEBGL,t.flipY),this.target===i.TEXTURE_CUBE_MAP){if(f.isArray(e)){const t=e,s=[i.TEXTURE_CUBE_MAP_POSITIVE_X,i.TEXTURE_CUBE_MAP_NEGATIVE_X,i.TEXTURE_CUBE_MAP_POSITIVE_Y,i.TEXTURE_CUBE_MAP_NEGATIVE_Y,i.TEXTURE_CUBE_MAP_POSITIVE_Z,i.TEXTURE_CUBE_MAP_NEGATIVE_Z];for(let e=0,r=s.length;e<r;e++)i.texImage2D(s[e],0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,t[e])}}else i.texImage2D(i.TEXTURE_2D,0,i.RGBA,i.RGBA,i.UNSIGNED_BYTE,e);i.bindTexture(this.target,null)}setProps(e){const t=this.gl;if(t.bindTexture(this.target,this.texture),e.minFilter){const i=To(t,e.minFilter);i&&(t.texParameteri(this.target,t.TEXTURE_MIN_FILTER,i),i!==t.NEAREST_MIPMAP_NEAREST&&i!==t.LINEAR_MIPMAP_NEAREST&&i!==t.NEAREST_MIPMAP_LINEAR&&i!==t.LINEAR_MIPMAP_LINEAR||t.generateMipmap(this.target))}if(e.magFilter){const i=To(t,e.magFilter);i&&t.texParameteri(this.target,t.TEXTURE_MAG_FILTER,i)}if(e.wrapS){const i=To(t,e.wrapS);i&&t.texParameteri(this.target,t.TEXTURE_WRAP_S,i)}if(e.wrapT){const i=To(t,e.wrapT);i&&t.texParameteri(this.target,t.TEXTURE_WRAP_T,i)}t.bindTexture(this.target,null)}bind(e){if(this.allocated){if(this.texture){const t=this.gl;return t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,this.texture),!0}return!1}}unbind(e){if(this.allocated&&this.texture){const t=this.gl;t.activeTexture(t["TEXTURE"+e]),t.bindTexture(this.target,null)}}destroy(){this.allocated&&this.texture&&(this.gl.deleteTexture(this.texture),this.texture=null)}}function No(e){if(!Io(e.width)||!Io(e.height)){const t=document.createElement("canvas");t.width=Oo(e.width),t.height=Oo(e.height),t.getContext("2d").drawImage(e,0,0,e.width,e.height,0,0,t.width,t.height),e=t}return e}function Io(e){return 0==(e&e-1)}function Oo(e){--e;for(let t=1;t<32;t<<=1)e|=e>>t;return e+1}class ko extends A{get type(){return"Texture"}constructor(e,t={}){super(e,t),this._state=new me({texture:new Fo(this.scene.canvas.gl),matrix:u.identityMat4(),hasMatrix:t.translate&&(0!==t.translate[0]||0!==t.translate[1])||!!t.rotate||t.scale&&(0!==t.scale[0]||0!==t.scale[1]),minFilter:this._checkMinFilter(t.minFilter),magFilter:this._checkMagFilter(t.magFilter),wrapS:this._checkWrapS(t.wrapS),wrapT:this._checkWrapT(t.wrapT),flipY:this._checkFlipY(t.flipY),encoding:this._checkEncoding(t.encoding)}),this._src=null,this._image=null,this._translate=u.vec2([0,0]),this._scale=u.vec2([1,1]),this._rotate=u.vec2([0,0]),this._matrixDirty=!1,this.translate=t.translate,this.scale=t.scale,this.rotate=t.rotate,t.src?this.src=t.src:t.image&&(this.image=t.image),d.memory.textures++}_checkMinFilter(e){return"linear"!==(e=e||"linearMipmapLinear")&&"linearMipmapNearest"!==e&&"linearMipmapLinear"!==e&&"nearestMipmapLinear"!==e&&"nearestMipmapNearest"!==e&&(this.error("Unsupported value for 'minFilter': '"+e+"' - supported values are 'linear', 'linearMipmapNearest', 'nearestMipmapNearest', 'nearestMipmapLinear' and 'linearMipmapLinear'. Defaulting to 'linearMipmapLinear'."),e="linearMipmapLinear"),e}_checkMagFilter(e){return"linear"!==(e=e||"linear")&&"nearest"!==e&&(this.error("Unsupported value for 'magFilter': '"+e+"' - supported values are 'linear' and 'nearest'. Defaulting to 'linear'."),e="linear"),e}_checkFilter(e){return"linear"!==(e=e||"linear")&&"nearest"!==e&&(this.error("Unsupported value for 'magFilter': '"+e+"' - supported values are 'linear' and 'nearest'. Defaulting to 'linear'."),e="linear"),e}_checkWrapS(e){return"clampToEdge"!==(e=e||"repeat")&&"mirroredRepeat"!==e&&"repeat"!==e&&(this.error("Unsupported value for 'wrapS': '"+e+"' - supported values are 'clampToEdge', 'mirroredRepeat' and 'repeat'. Defaulting to 'repeat'."),e="repeat"),e}_checkWrapT(e){return"clampToEdge"!==(e=e||"repeat")&&"mirroredRepeat"!==e&&"repeat"!==e&&(this.error("Unsupported value for 'wrapT': '"+e+"' - supported values are 'clampToEdge', 'mirroredRepeat' and 'repeat'. Defaulting to 'repeat'."),e="repeat"),e}_checkFlipY(e){return!!e}_checkEncoding(e){return"linear"!==(e=e||"linear")&&"sRGB"!==e&&"gamma"!==e&&(this.error("Unsupported value for 'encoding': '"+e+"' - supported values are 'linear', 'sRGB', 'gamma'. Defaulting to 'linear'."),e="linear"),e}_webglContextRestored(){this._state.texture=new Fo(this.scene.canvas.gl),this._image?this.image=this._image:this._src&&(this.src=this._src)}_update(){const e=this._state;if(this._matrixDirty){let t,i;0===this._translate[0]&&0===this._translate[1]||(t=u.translationMat4v([this._translate[0],this._translate[1],0],this._state.matrix)),1===this._scale[0]&&1===this._scale[1]||(i=u.scalingMat4v([this._scale[0],this._scale[1],1]),t=t?u.mulMat4(t,i):i),0!==this._rotate&&(i=u.rotationMat4v(.0174532925*this._rotate,[0,0,1]),t=t?u.mulMat4(t,i):i),t&&(e.matrix=t),this._matrixDirty=!1}this.glRedraw()}set image(e){this._image=No(e),this._image.crossOrigin="Anonymous",this._state.texture.setImage(this._image,this._state),this._state.texture.setProps(this._state),this._src=null,this.glRedraw()}get image(){return this._image}set src(e){this.scene.loading++,this.scene.canvas.spinner.processes++;const t=this;let i=new Image;i.onload=function(){i=No(i),t._state.texture.setImage(i,t._state),t._state.texture.setProps(t._state),t.scene.loading--,t.glRedraw(),t.scene.canvas.spinner.processes--},i.src=e,this._src=e,this._image=null}get src(){return this._src}set translate(e){this._translate.set(e||[0,0]),this._matrixDirty=!0,this._needUpdate()}get translate(){return this._translate}set scale(e){this._scale.set(e||[1,1]),this._matrixDirty=!0,this._needUpdate()}get scale(){return this._scale}set rotate(e){e=e||0,this._rotate!==e&&(this._rotate=e,this._matrixDirty=!0,this._needUpdate())}get rotate(){return this._rotate}get minFilter(){return this._state.minFilter}get magFilter(){return this._state.magFilter}get wrapS(){return this._state.wrapS}get wrapT(){return this._state.wrapT}get flipY(){return this._state.flipY}get encoding(){return this._state.encoding}destroy(){super.destroy(),this._state.texture&&this._state.texture.destroy(),this._state.destroy(),d.memory.textures--}}const Vo={IfcOpeningElement:{pickable:!1,visible:!1},IfcSpace:{colorize:[.137255,.403922,.870588],pickable:!1,visible:!1,opacity:.4},IfcWindow:{colorize:[.137255,.403922,.870588],opacity:.3},IfcPlate:{colorize:[.8470588235,.427450980392,0,.5],opacity:.3},DEFAULT:{}};function jo(e,t={}){const i="lightgrey",s=t.hoverColor||"rgba(0,0,0,0.4)";var r=500,o=r+r/3,a=o/24;const n=[{boundary:[6,6,6,6],color:t.frontColor||t.color||"#55FF55"},{boundary:[18,6,6,6],color:t.backColor||t.color||"#55FF55"},{boundary:[12,6,6,6],color:t.leftColor||t.color||"#FF5555"},{boundary:[0,6,6,6],color:t.rightColor||t.color||"#FF5555"},{boundary:[6,0,6,6],color:t.topColor||t.color||"#7777FF"},{boundary:[6,12,6,6],color:t.bottomColor||t.color||"#7777FF"}],l=[{label:"front",boundaries:[[7,7,4,4]],dir:[0,1,0],up:[0,0,1]},{label:"back",boundaries:[[19,7,4,4]],dir:[0,-1,0],up:[0,0,1]},{label:"right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,0,1]},{label:"left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,0,1]},{label:"top",boundaries:[[7,1,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"bottom",boundaries:[[7,13,4,4]],dir:[0,0,1],up:[0,-1,0]},{boundaries:[[7,5,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,0,-1],up:[1,0,1]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,-1],up:[0,-1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,0,-1],up:[-1,0,1]},{boundaries:[[7,11,4,2]],dir:[0,1,1],up:[0,-1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,0,1],up:[-1,0,1]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,0,1],up:[1,0,1]},{boundaries:[[5,7,2,4]],dir:[1,1,0],up:[0,0,1]},{boundaries:[[11,7,2,4]],dir:[-1,1,0],up:[0,0,1]},{boundaries:[[17,7,2,4]],dir:[-1,-1,0],up:[0,0,1]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,-1,0],up:[0,0,1]},{boundaries:[[5,11,2,2]],dir:[1,1,1],up:[-1,-1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,-1,1],up:[-1,1,1]},{boundaries:[[5,5,2,2]],dir:[1,1,-1],up:[1,1,1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,-1,1],up:[1,1,1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,-1],up:[-1,-1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,1],up:[1,-1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,-1],up:[1,-1,1]},{boundaries:[[11,5,2,2]],dir:[-1,1,-1],up:[-1,1,1]}];t.frontColor||t.color,t.backColor||t.color,t.leftColor||t.color,t.rightColor||t.color,t.topColor||t.color,t.bottomColor||t.color;const h=[{label:"front",boundaries:[[7,7,4,4]],dir:[0,0,-1],up:[0,1,0]},{label:"back",boundaries:[[19,7,4,4]],dir:[0,0,1],up:[0,1,0]},{label:"right",boundaries:[[13,7,4,4]],dir:[-1,0,0],up:[0,1,0]},{label:"left",boundaries:[[1,7,4,4]],dir:[1,0,0],up:[0,1,0]},{label:"top",boundaries:[[7,1,4,4]],dir:[0,-1,0],up:[0,0,-1]},{label:"bottom",boundaries:[[7,13,4,4]],dir:[0,1,0],up:[0,0,1]},{boundaries:[[7,5,4,2]],dir:[0,-1,-1],up:[0,1,-1]},{boundaries:[[1,6,4,1],[6,1,1,4]],dir:[1,-1,0],up:[1,1,0]},{boundaries:[[7,0,4,1],[19,6,4,1]],dir:[0,-1,1],up:[0,1,1]},{boundaries:[[13,6,4,1],[11,1,1,4]],dir:[-1,-1,0],up:[-1,1,0]},{boundaries:[[7,11,4,2]],dir:[0,1,-1],up:[0,1,1]},{boundaries:[[1,11,4,1],[6,13,1,4]],dir:[1,1,0],up:[-1,1,0]},{boundaries:[[7,17,4,1],[19,11,4,1]],dir:[0,1,1],up:[0,1,-1]},{boundaries:[[13,11,4,1],[11,13,1,4]],dir:[-1,1,0],up:[1,1,0]},{boundaries:[[5,7,2,4]],dir:[1,0,-1],up:[0,1,0]},{boundaries:[[11,7,2,4]],dir:[-1,0,-1],up:[0,1,0]},{boundaries:[[17,7,2,4]],dir:[-1,0,1],up:[0,1,0]},{boundaries:[[0,7,1,4],[23,7,1,4]],dir:[1,0,1],up:[0,1,0]},{boundaries:[[5,11,2,2]],dir:[1,1,-1],up:[-1,1,1]},{boundaries:[[23,11,1,1],[6,17,1,1],[0,11,1,1]],dir:[1,1,1],up:[-1,1,-1]},{boundaries:[[5,5,2,2]],dir:[1,-1,-1],up:[1,1,-1]},{boundaries:[[11,17,1,1],[17,11,2,1]],dir:[-1,1,1],up:[1,1,-1]},{boundaries:[[17,6,2,1],[11,0,1,1]],dir:[-1,-1,1],up:[-1,1,1]},{boundaries:[[11,11,2,2]],dir:[-1,1,-1],up:[1,1,1]},{boundaries:[[0,6,1,1],[6,0,1,1],[23,6,1,1]],dir:[1,-1,1],up:[1,1,1]},{boundaries:[[11,5,2,2]],dir:[-1,-1,-1],up:[-1,1,-1]}];for(let e=0,t=l.length;e<t;e++)u.normalizeVec3(l[e].dir,l[e].dir),u.normalizeVec3(h[e].dir,h[e].dir);var c=h;this._textureCanvas=document.createElement("canvas"),this._textureCanvas.width=o,this._textureCanvas.height=r,this._textureCanvas.style.width=o+"px",this._textureCanvas.style.height="500px",this._textureCanvas.style.padding="0",this._textureCanvas.style.margin="0",this._textureCanvas.style.top="0",this._textureCanvas.style.background=i,this._textureCanvas.style.position="absolute",this._textureCanvas.style.opacity="1.0",this._textureCanvas.style.visibility="hidden",this._textureCanvas.style["z-index"]=2e6,document.getElementsByTagName("body")[0].appendChild(this._textureCanvas);const d=this._textureCanvas.getContext("2d");function p(){for(let e=0,t=n.length;e<t;e++){const t=n[e],i=t.boundary,s=Math.round(i[0]*a),r=Math.round(i[1]*a),o=Math.round(i[2]*a),l=Math.round(i[3]*a);d.fillStyle=t.color,d.fillRect(s,r,o,l)}for(let n=0,l=c.length;n<l;n++){let l,h,u,p;const f=c[n],g=f.boundaries;for(var e=0,t=g.length;e<t;e++){const t=g[e];l=Math.round(t[0]*a),h=Math.round(t[1]*a),u=Math.round(t[2]*a),p=Math.round(t[3]*a),f.highlighted&&(d.fillStyle=f.highlighted?s:f.color||i,d.fillRect(l,h,u,p))}if(f.label){d.fillStyle="black",d.font="60px sans-serif",d.textAlign="center";var r=l+.5*u,o=h+.7*p;d.fillText(_(f.label),r,o,80)}}}var _=function(){const t={yUp:{front:"+Z",back:"-Z",right:"+X",left:"-X",top:"+Y",bottom:"-Y"},en:{front:"FRONT",back:"BACK",right:"RIGHT",left:"LEFT",top:"TOP",bottom:"BOTTOM"}};return function(i){var s;return(s=t[e.language||"en"])&&s[i]||i}}();this.setZUp=function(){c=l,this.clear()},this.setYUp=function(){c=h,this.clear()},this.clear=function(){d.fillStyle=i,d.fillRect(0,0,o,r);for(var e=0,t=c.length;e<t;e++)c[e].highlighted=!1;p()},this.getArea=function(e){const t=e[0]*o,i=r-e[1]*r;for(var s=0,n=c.length;s<n;s++){const e=c[s].boundaries;for(var l=0,h=e.length;l<h;l++){const r=e[l];if(t>=r[0]*a&&t<=(r[0]+r[2])*a&&i>=r[1]*a&&i<=(r[1]+r[3])*a)return s}}return-1},this.setAreaHighlighted=function(e,t){var i=c[e];if(!i)throw"Area not found: "+e;i.highlighted=!!t,p()},this.getAreaDir=function(e){var t=c[e];if(!t)throw"Unknown area: "+e;return t.dir},this.getAreaUp=function(e){var t=c[e];if(!t)throw"Unknown area: "+e;return t.up},this.getImage=function(){return this._textureCanvas},this.destroy=function(){this._textureCanvas&&(this._textureCanvas.parentNode.removeChild(this._textureCanvas),this._textureCanvas=null)},this.clear()}class zo extends a{constructor(e,t={}){super("NavCube",e,t),e.navCube=this;try{this._navCubeScene=new pt(e,{canvasId:t.canvasId,canvasElement:t.canvasElement,transparent:!0}),this._navCubeCanvas=this._navCubeScene.canvas.canvas,this._navCubeScene.input.keyboardEnabled=!1}catch(e){return void this.error(e)}const i=this._navCubeScene;i.clearLights(),new Oe(i,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Oe(i,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Oe(i,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._navCubeCamera=i.camera,this._navCubeCamera.ortho.scale=7,this._navCubeCamera.ortho.near=.1,this._navCubeCamera.ortho.far=2e3,this._zUp=Boolean(e.camera.zUp);var s=this;this._synchCamera=function(){var t=u.rotationMat4c(-90*u.DEGTORAD,1,0,0),i=u.vec3(),r=u.vec3(),o=u.vec3();return function(){var a=e.camera.eye,n=e.camera.look,l=e.camera.up;i=u.mulVec3Scalar(u.normalizeVec3(u.subVec3(a,n,i)),5),s._zUp?(u.transformVec3(t,i,r),u.transformVec3(t,l,o),s._navCubeCamera.look=[0,0,0],s._navCubeCamera.eye=u.transformVec3(t,i,r),s._navCubeCamera.up=u.transformPoint3(t,l,o)):(s._navCubeCamera.look=[0,0,0],s._navCubeCamera.eye=i,s._navCubeCamera.up=l)}}(),this._cubeTextureCanvas=new jo(e,t),this._cubeSampler=new ko(i,{image:this._cubeTextureCanvas.getImage(),flipY:!0,wrapS:"clampToEdge",wrapT:"clampToEdge"}),this._cubeMesh=new ri(i,{geometry:new Ke(i,{primitive:"triangles",normals:[0,0,1,0,0,1,0,0,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,0,0,1,0,0,1,0,0,1,0,0,1,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1,0,0,0,-1,0,0,-1,0,0,-1,0,0,-1],positions:[1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,1,1,-1,-1,1,1,-1,1,1,1,1,1,-1,-1,1,-1,-1,1,1,-1,1,1,-1,1,-1,-1,-1,-1,-1,-1,1,-1,-1,-1,1,-1,-1,1,-1,1,-1,-1,1,1,-1,-1,-1,-1,-1,-1,1,-1,1,1,-1],uv:[.5,.6666,.25,.6666,.25,.3333,.5,.3333,.5,.6666,.5,.3333,.75,.3333,.75,.6666,.5,.6666,.5,1,.25,1,.25,.6666,.25,.6666,0,.6666,0,.3333,.25,.3333,.25,0,.5,0,.5,.3333,.25,.3333,.75,.3333,1,.3333,1,.6666,.75,.6666],indices:[0,1,2,0,2,3,4,5,6,4,6,7,8,9,10,8,10,11,12,13,14,12,14,15,16,17,18,16,18,19,20,21,22,20,22,23]}),material:new et(i,{diffuse:[.4,.4,.4],specular:[.4,.4,.4],emissive:[.6,.6,.6],diffuseMap:this._cubeSampler,emissiveMap:this._cubeSampler}),visible:!0,edges:!0}),this._shadow=new ri(i,{geometry:new Ke(i,ai({center:[0,0,0],radiusTop:.001,radiusBottom:1.4,height:.01,radialSegments:20,heightSegments:1,openEnded:!0})),material:new et(i,{diffuse:[0,0,0],specular:[0,0,0],emissive:[0,0,0],alpha:.5}),position:[0,-1.5,0],visible:!0,pickable:!1,backfaces:!1}),this._onCameraMatrix=e.camera.on("matrix",this._synchCamera),this._onCameraWorldAxis=e.camera.on("worldAxis",(()=>{e.camera.zUp?(this._zUp=!0,this._cubeTextureCanvas.setZUp(),this._repaint(),this._synchCamera()):e.camera.yUp&&(this._zUp=!1,this._cubeTextureCanvas.setYUp(),this._repaint(),this._synchCamera())})),this._onCameraFOV=e.camera.perspective.on("fov",(e=>{this._synchProjection&&(this._navCubeCamera.perspective.fov=e)})),this._onCameraProjection=e.camera.on("projection",(e=>{this._synchProjection&&(this._navCubeCamera.projection=e)}));var r=-1;function o(e){var t=[0,0];if(e){for(var i=e.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t}var a,n,l=null,h=null,c=!1,d=!1;s._navCubeCanvas.addEventListener("mouseenter",s._onMouseEnter=function(e){d=!0}),s._navCubeCanvas.addEventListener("mouseleave",s._onMouseLeave=function(e){d=!1}),s._navCubeCanvas.addEventListener("mousedown",s._onMouseDown=function(e){if(1===e.which){l=e.x,h=e.y,a=e.clientX,n=e.clientY;var t=o(e),s=i.pick({canvasPos:t});c=!!s}}),document.addEventListener("mouseup",s._onMouseUp=function(e){if(1===e.which&&(c=!1,null!==l)){var t=o(e),a=i.pick({canvasPos:t,pickSurface:!0});if(a&&a.uv){var n=s._cubeTextureCanvas.getArea(a.uv);if(n>=0&&(document.body.style.cursor="pointer",r>=0&&(s._cubeTextureCanvas.setAreaHighlighted(r,!1),s._repaint(),r=-1),n>=0)){if(s._cubeTextureCanvas.setAreaHighlighted(n,!0),r=n,s._repaint(),e.x<l-3||e.x>l+3||e.y<h-3||e.y>h+3)return;var u=s._cubeTextureCanvas.getAreaDir(n);if(u){var d=s._cubeTextureCanvas.getAreaUp(n);p(u,d,(function(){r>=0&&(s._cubeTextureCanvas.setAreaHighlighted(r,!1),s._repaint(),r=-1);var e=i.pick({canvasPos:t,pickSurface:!0});if(e&&e.uv){var o=s._cubeTextureCanvas.getArea(e.uv);void 0!==o&&(document.body.style.cursor="pointer",r>=0&&(s._cubeTextureCanvas.setAreaHighlighted(r,!1),s._repaint(),r=-1),o>=0&&(s._cubeTextureCanvas.setAreaHighlighted(o,!0),r=o,s._repaint()))}}))}}}}}),document.addEventListener("mousemove",s._onMouseMove=function(t){if(r>=0&&(s._cubeTextureCanvas.setAreaHighlighted(r,!1),s._repaint(),r=-1),1!==t.buttons||c){if(c){var l=t.clientX,h=t.clientY;return document.body.style.cursor="move",void function(t,i){var s=-.5*(t-a),r=-.5*(i-n);e.camera.orbitYaw(s),e.camera.orbitPitch(-r),a=t,n=i}(l,h)}if(d){var u=o(t),p=i.pick({canvasPos:u,pickSurface:!0});if(p){if(p.uv){document.body.style.cursor="pointer";var _=s._cubeTextureCanvas.getArea(p.uv);if(_===r)return;r>=0&&s._cubeTextureCanvas.setAreaHighlighted(r,!1),_>=0&&(s._cubeTextureCanvas.setAreaHighlighted(_,!0),s._repaint(),r=_)}}else document.body.style.cursor="default",r>=0&&(s._cubeTextureCanvas.setAreaHighlighted(r,!1),s._repaint(),r=-1)}}});var p=function(){var t=u.vec3();return function(i,r,o){var a=s._fitVisible?e.scene.getAABB(e.scene.visibleObjectIds):e.scene.aabb,n=u.getAABB3Diag(a);u.getAABB3Center(a,t);var l=Math.abs(n/Math.tan(27.5));e.cameraControl.pivotPos=t,s._cameraFly?e.cameraFlight.flyTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.3*n,fitFOV:s._cameraFitFOV,duration:s._cameraFlyDuration},o):e.cameraFlight.jumpTo({look:t,eye:[t[0]-l*i[0],t[1]-l*i[1],t[2]-l*i[2]],up:r||[0,1,0],orthoScale:1.3*n,fitFOV:s._cameraFitFOV},o)}}();this.setVisible(t.visible),this.setCameraFitFOV(t.cameraFitFOV),this.setCameraFly(t.cameraFly),this.setCameraFlyDuration(t.cameraFlyDuration),this.setFitVisible(t.fitVisible),this.setSynchProjection(t.synchProjection)}send(e,t){switch(e){case"language":this._cubeTextureCanvas.clear(),this._repaint()}}_repaint(){const e=this._cubeTextureCanvas.getImage();this._cubeMesh.material.diffuseMap.image=e,this._cubeMesh.material.emissiveMap.image=e}setVisible(e=!0){this._navCubeCanvas&&(this._cubeMesh.visible=e,this._shadow.visible=e,this._navCubeCanvas.style.visibility=e?"visible":"hidden")}getVisible(){return!!this._navCubeCanvas&&this._cubeMesh.visible}setFitVisible(e=!1){this._fitVisible=e}getFitVisible(){return this._fitVisible}setCameraFly(e=!0){this._cameraFly=e}getCameraFly(){return this._cameraFly}setCameraFitFOV(e=45){this._cameraFitFOV=e}getCameraFitFOV(){return this._cameraFitFOV}setCameraFlyDuration(e=.5){this._cameraFlyDuration=e}getCameraFlyDuration(){return this._cameraFlyDuration}setSynchProjection(e=!1){this._synchProjection=e}getSynchProjection(){return this._synchProjection}destroy(){this._navCubeCanvas&&(this.viewer.camera.off(this._onCameraMatrix),this.viewer.camera.off(this._onCameraWorldAxis),this.viewer.camera.perspective.off(this._onCameraFOV),this.viewer.camera.off(this._onCameraProjection),this._navCubeCanvas.removeEventListener("mouseenter",this._onMouseEnter),this._navCubeCanvas.removeEventListener("mouseleave",this._onMouseLeave),this._navCubeCanvas.removeEventListener("mousedown",this._onMouseDown),document.removeEventListener("mousemove",this._onMouseMove),document.removeEventListener("mouseup",this._onMouseUp),this._navCubeCanvas=null,this._cubeTextureCanvas.destroy(),this._cubeTextureCanvas=null,this._onMouseEnter=null,this._onMouseLeave=null,this._onMouseDown=null,this._onMouseMove=null,this._onMouseUp=null),this._navCubeScene.destroy(),this._navCubeScene=null,this._cubeMesh=null,this._shadow=null,super.destroy()}}u.vec3();function Uo(e={}){let t=e.radius||1;t<0&&(console.error("negative radius not allowed - will invert"),t*=-1),t*=.5;let i=e.tube||.3;i<0&&(console.error("negative tube not allowed - will invert"),i*=-1);let s=e.radialSegments||32;s<0&&(console.error("negative radialSegments not allowed - will invert"),s*=-1),s<4&&(s=4);let r=e.tubeSegments||24;r<0&&(console.error("negative tubeSegments not allowed - will invert"),r*=-1),r<4&&(r=4);let o=e.arc||2*Math.PI;o<0&&(console.warn("negative arc not allowed - will invert"),o*=-1),o>360&&(o=360);const a=e.center;let n=a?a[0]:0,l=a?a[1]:0;const h=a?a[2]:0,c=[],d=[],p=[],_=[];let g,m,v,b,P,y,M,x,w,E,A,C;for(x=0;x<=r;x++)for(M=0;M<=s;M++)g=M/s*o,m=.785398+x/r*Math.PI*2,n=t*Math.cos(g),l=t*Math.sin(g),v=(t+i*Math.cos(m))*Math.cos(g),b=(t+i*Math.cos(m))*Math.sin(g),P=i*Math.sin(m),c.push(v+n),c.push(b+l),c.push(P+h),p.push(1-M/s),p.push(x/r),y=u.normalizeVec3(u.subVec3([v,b,P],[n,l,h],[]),[]),d.push(y[0]),d.push(y[1]),d.push(y[2]);for(x=1;x<=r;x++)for(M=1;M<=s;M++)w=(s+1)*x+M-1,E=(s+1)*(x-1)+M-1,A=(s+1)*(x-1)+M,C=(s+1)*x+M,_.push(w),_.push(E),_.push(A),_.push(A),_.push(C),_.push(w);return f.apply(e,{positions:c,normals:d,uv:p,indices:_})}const Go=new Float64Array([0,0,1]),Xo=new Float64Array(4);class Ho{constructor(e){this.id=null,this._viewer=e.viewer,this._visible=!1,this._pos=u.vec3(),this._rtcCenter=u.vec3(),this._rtcPos=u.vec3(),this._baseDir=u.vec3(),this._rootNode=null,this._displayMeshes=null,this._affordanceMeshes=null,this._ignoreNextSectionPlaneDirUpdate=!1,this._createNodes(),this._bindEvents()}_setSectionPlane(e){this._sectionPlane&&(this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._onSectionPlanePos=null,this._onSectionPlaneDir=null,this._sectionPlane=null),e&&(this.id=e.id,this._setPos(e.pos),this._setDir(e.dir),this._sectionPlane=e,this._onSectionPlanePos=e.on("pos",(()=>{this._setPos(this._sectionPlane.pos)})),this._onSectionPlaneDir=e.on("dir",(()=>{this._ignoreNextSectionPlaneDirUpdate?this._ignoreNextSectionPlaneDirUpdate=!1:this._setDir(this._sectionPlane.dir)})))}get sectionPlane(){return this._sectionPlane}_setPos(e){this._pos.set(e),function(e,t,i){const s=Float32Array.from([e[0]])[0],r=e[0]-s,o=Float32Array.from([e[1]])[0],a=e[1]-o,n=Float32Array.from([e[2]])[0],l=e[2]-n;t[0]=s,t[1]=o,t[2]=n,i[0]=r,i[1]=a,i[2]=l}(this._pos,this._rtcCenter,this._rtcPos),this._rootNode.rtcCenter=this._rtcCenter,this._rootNode.position=this._rtcPos}_setDir(e){this._baseDir.set(e),this._rootNode.quaternion=u.vec3PairToQuaternion(Go,e,Xo)}_setSectionPlaneDir(e){this._sectionPlane&&(this._ignoreNextSectionPlaneDirUpdate=!0,this._sectionPlane.dir=e)}setVisible(e=!0){if(this._visible!==e){var t;for(t in this._visible=e,this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].visible=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].visible=e)}}getVisible(){return this._visible}setCulled(e){var t;for(t in this._displayMeshes)this._displayMeshes.hasOwnProperty(t)&&(this._displayMeshes[t].culled=e);if(!e)for(t in this._affordanceMeshes)this._affordanceMeshes.hasOwnProperty(t)&&(this._affordanceMeshes[t].culled=e)}_createNodes(){const e=!1,t=this._viewer.scene,i=.01;this._rootNode=new Lo(t,{position:[0,0,0],scale:[5,5,5]});const s=this._rootNode,r={arrowHead:new Ke(s,ai({radiusTop:.001,radiusBottom:.07,radialSegments:32,heightSegments:1,height:.2,openEnded:!1})),arrowHeadBig:new Ke(s,ai({radiusTop:.001,radiusBottom:.09,radialSegments:32,heightSegments:1,height:.25,openEnded:!1})),arrowHeadHandle:new Ke(s,ai({radiusTop:.09,radiusBottom:.09,radialSegments:8,heightSegments:1,height:.37,openEnded:!1})),curve:new Ke(s,Uo({radius:.8,tube:i,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),curveHandle:new Ke(s,Uo({radius:.8,tube:.06,radialSegments:64,tubeSegments:14,arc:2*Math.PI/4})),hoop:new Ke(s,Uo({radius:.8,tube:i,radialSegments:64,tubeSegments:8,arc:2*Math.PI})),axis:new Ke(s,ai({radiusTop:i,radiusBottom:i,radialSegments:20,heightSegments:1,height:1,openEnded:!1})),axisHandle:new Ke(s,ai({radiusTop:.08,radiusBottom:.08,radialSegments:20,heightSegments:1,height:1,openEnded:!1}))},o={pickable:new et(s,{diffuse:[1,1,0],alpha:0,alphaMode:"blend"}),red:new et(s,{diffuse:[1,0,0],emissive:[1,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightRed:new it(s,{edges:!1,fill:!0,fillColor:[1,0,0],fillAlpha:.6}),green:new et(s,{diffuse:[0,1,0],emissive:[0,1,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightGreen:new it(s,{edges:!1,fill:!0,fillColor:[0,1,0],fillAlpha:.6}),blue:new et(s,{diffuse:[0,0,1],emissive:[0,0,1],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80,lineWidth:2}),highlightBlue:new it(s,{edges:!1,fill:!0,fillColor:[0,0,1],fillAlpha:.2}),center:new et(s,{diffuse:[0,0,0],emissive:[0,0,0],ambient:[0,0,0],specular:[.6,.6,.3],shininess:80}),highlightBall:new it(s,{edges:!1,fill:!0,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1}),highlightPlane:new it(s,{edges:!0,edgeWidth:3,fill:!1,fillColor:[.5,.5,.5],fillAlpha:.5,vertices:!1})};this._displayMeshes={plane:s.addChild(new ri(s,{geometry:new Ke(s,{primitive:"triangles",positions:[.5,.5,0,.5,-.5,0,-.5,-.5,0,-.5,.5,0,.5,.5,-0,.5,-.5,-0,-.5,-.5,-0,-.5,.5,-0],indices:[0,1,2,2,3,0]}),material:new et(s,{emissive:[0,0,0],diffuse:[0,0,0],backfaces:!0}),opacity:.6,ghosted:!0,ghostMaterial:new it(s,{edges:!1,filled:!0,fillColor:[1,1,0],edgeColor:[0,0,0],fillAlpha:.1,backfaces:!0}),pickable:!1,collidable:!0,clippable:!1,visible:!1,scale:[2.4,2.4,1]}),e),planeFrame:s.addChild(new ri(s,{geometry:new Ke(s,Uo({center:[0,0,0],radius:1.7,tube:.02,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new et(s,{emissive:[0,0,0],diffuse:[0,0,0],specular:[0,0,0],shininess:0}),highlightMaterial:new it(s,{edges:!1,edgeColor:[0,0,0],filled:!0,fillColor:[.8,.8,.8],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,.1],rotation:[0,0,45]}),e),xCurve:s.addChild(new ri(s,{geometry:r.curve,material:o.red,matrix:function(){const e=u.rotationMat4v(90*u.DEGTORAD,[0,1,0],u.identityMat4()),t=u.rotationMat4v(270*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),e),xCurveHandle:s.addChild(new ri(s,{geometry:r.curveHandle,material:o.pickable,matrix:function(){const e=u.rotationMat4v(90*u.DEGTORAD,[0,1,0],u.identityMat4()),t=u.rotationMat4v(270*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),e),xCurveArrow1:s.addChild(new ri(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=u.translateMat4c(0,-.07,-.8,u.identityMat4()),t=u.scaleMat4v([.6,.6,.6],u.identityMat4()),i=u.rotationMat4v(0*u.DEGTORAD,[0,0,1],u.identityMat4());return u.mulMat4(u.mulMat4(e,t,u.identityMat4()),i,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),xCurveArrow2:s.addChild(new ri(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=u.translateMat4c(0,-.8,-.07,u.identityMat4()),t=u.scaleMat4v([.6,.6,.6],u.identityMat4()),i=u.rotationMat4v(90*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(u.mulMat4(e,t,u.identityMat4()),i,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),yCurve:s.addChild(new ri(s,{geometry:r.curve,material:o.green,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),e),yCurveHandle:s.addChild(new ri(s,{geometry:r.curveHandle,material:o.pickable,rotation:[-90,0,0],pickable:!0,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),e),yCurveArrow1:s.addChild(new ri(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=u.translateMat4c(.07,0,-.8,u.identityMat4()),t=u.scaleMat4v([.6,.6,.6],u.identityMat4()),i=u.rotationMat4v(90*u.DEGTORAD,[0,0,1],u.identityMat4());return u.mulMat4(u.mulMat4(e,t,u.identityMat4()),i,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),yCurveArrow2:s.addChild(new ri(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=u.translateMat4c(.8,0,-.07,u.identityMat4()),t=u.scaleMat4v([.6,.6,.6],u.identityMat4()),i=u.rotationMat4v(90*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(u.mulMat4(e,t,u.identityMat4()),i,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),zCurve:s.addChild(new ri(s,{geometry:r.curve,material:o.blue,matrix:u.rotationMat4v(180*u.DEGTORAD,[1,0,0],u.identityMat4()),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zCurveHandle:s.addChild(new ri(s,{geometry:r.curveHandle,material:o.pickable,matrix:u.rotationMat4v(180*u.DEGTORAD,[1,0,0],u.identityMat4()),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),zCurveCurveArrow1:s.addChild(new ri(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=u.translateMat4c(.8,-.07,0,u.identityMat4()),t=u.scaleMat4v([.6,.6,.6],u.identityMat4());return u.mulMat4(e,t,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),zCurveArrow2:s.addChild(new ri(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=u.translateMat4c(.05,-.8,0,u.identityMat4()),t=u.scaleMat4v([.6,.6,.6],u.identityMat4()),i=u.rotationMat4v(90*u.DEGTORAD,[0,0,1],u.identityMat4());return u.mulMat4(u.mulMat4(e,t,u.identityMat4()),i,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),center:s.addChild(new ri(s,{geometry:new Ke(s,ni({radius:.05})),material:o.center,pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),xAxisArrow:s.addChild(new ri(s,{geometry:r.arrowHead,material:o.red,matrix:function(){const e=u.translateMat4c(0,1.1,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[0,0,1],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),xAxisArrowHandle:s.addChild(new ri(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=u.translateMat4c(0,1.1,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[0,0,1],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),xAxis:s.addChild(new ri(s,{geometry:r.axis,material:o.red,matrix:function(){const e=u.translateMat4c(0,.5,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[0,0,1],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),xAxisHandle:s.addChild(new ri(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=u.translateMat4c(0,.5,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[0,0,1],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),yAxisArrow:s.addChild(new ri(s,{geometry:r.arrowHead,material:o.green,matrix:function(){const e=u.translateMat4c(0,1.1,0,u.identityMat4()),t=u.rotationMat4v(180*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),yAxisArrowHandle:s.addChild(new ri(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=u.translateMat4c(0,1.1,0,u.identityMat4()),t=u.rotationMat4v(180*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1,opacity:.2}),e),yShaft:s.addChild(new ri(s,{geometry:r.axis,material:o.green,position:[0,-.5,0],pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),yShaftHandle:s.addChild(new ri(s,{geometry:r.axisHandle,material:o.pickable,position:[0,-.5,0],pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:s.addChild(new ri(s,{geometry:r.arrowHead,material:o.blue,matrix:function(){const e=u.translateMat4c(0,1.1,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[.8,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrowHandle:s.addChild(new ri(s,{geometry:r.arrowHeadHandle,material:o.pickable,matrix:function(){const e=u.translateMat4c(0,1.1,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[.8,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!0,collidable:!0,clippable:!1,visible:!1}),e),zShaft:s.addChild(new ri(s,{geometry:r.axis,material:o.blue,matrix:function(){const e=u.translateMat4c(0,.5,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),clippable:!1,pickable:!1,collidable:!0,visible:!1}),e),zAxisHandle:s.addChild(new ri(s,{geometry:r.axisHandle,material:o.pickable,matrix:function(){const e=u.translateMat4c(0,.5,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),clippable:!1,pickable:!0,collidable:!0,visible:!1}),e)},this._affordanceMeshes={planeFrame:s.addChild(new ri(s,{geometry:new Ke(s,Uo({center:[0,0,0],radius:2,tube:i,radialSegments:4,tubeSegments:4,arc:2*Math.PI})),material:new et(s,{ambient:[1,1,1],diffuse:[0,0,0],emissive:[1,1,0]}),highlighted:!0,highlightMaterial:new it(s,{edges:!1,filled:!0,fillColor:[1,1,0],fillAlpha:1}),pickable:!1,collidable:!1,clippable:!1,visible:!1,scale:[1,1,1],rotation:[0,0,45]}),e),xHoop:s.addChild(new ri(s,{geometry:r.hoop,material:o.red,highlighted:!0,highlightMaterial:o.highlightRed,matrix:function(){const e=u.rotationMat4v(90*u.DEGTORAD,[0,1,0],u.identityMat4()),t=u.rotationMat4v(270*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),yHoop:s.addChild(new ri(s,{geometry:r.hoop,material:o.green,highlighted:!0,highlightMaterial:o.highlightGreen,rotation:[-90,0,0],pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zHoop:s.addChild(new ri(s,{geometry:r.hoop,material:o.blue,highlighted:!0,highlightMaterial:o.highlightBlue,matrix:u.rotationMat4v(180*u.DEGTORAD,[1,0,0],u.identityMat4()),pickable:!1,collidable:!0,clippable:!1,backfaces:!0,visible:!1}),e),xAxisArrow:s.addChild(new ri(s,{geometry:r.arrowHeadBig,material:o.red,matrix:function(){const e=u.translateMat4c(0,1.1,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[0,0,1],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),yAxisArrow:s.addChild(new ri(s,{geometry:r.arrowHeadBig,material:o.green,matrix:function(){const e=u.translateMat4c(0,1.1,0,u.identityMat4()),t=u.rotationMat4v(180*u.DEGTORAD,[1,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e),zAxisArrow:s.addChild(new ri(s,{geometry:r.arrowHeadBig,material:o.blue,matrix:function(){const e=u.translateMat4c(0,1.1,0,u.identityMat4()),t=u.rotationMat4v(-90*u.DEGTORAD,[.8,0,0],u.identityMat4());return u.mulMat4(t,e,u.identityMat4())}(),pickable:!1,collidable:!0,clippable:!1,visible:!1}),e)}}_bindEvents(){const e=this;var t=!1;const i=this._rootNode;var s=null,r=null;const o=u.vec2(),a=u.vec3([1,0,0]),n=u.vec3([0,1,0]),l=u.vec3([0,0,1]),h=this._viewer.scene.canvas.canvas,c=this._viewer.camera,d=this._viewer.scene;{const e=u.vec3([0,0,0]);let t=-1;this._onCameraViewMatrix=d.camera.on("viewMatrix",(()=>{})),this._onCameraProjMatrix=d.camera.on("projMatrix",(()=>{})),this._onSceneTick=d.on("tick",(()=>{const s=Math.abs(u.lenVec3(u.subVec3(d.camera.eye,this._pos,e)));if(s!==t&&"perspective"===c.projection){const e=Math.tan(c.perspective.fov*u.DEGTORAD)*s*.07;i.scale=[e,e,e],t=s}if("ortho"===c.projection){const e=c.ortho.scale/10;i.scale=[e,e,e],t=s}}))}const p=function(){const e=new Float64Array(2);return function(t){if(t){for(var i=t.target,s=0,r=0;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;e[0]=t.pageX-s,e[1]=t.pageY-r}else t=window.event,e[0]=t.x,e[1]=t.y;return e}}(),_=function(){const t=u.mat4();return function(i,s){return u.quaternionToMat4(e._rootNode.quaternion,t),u.transformVec3(t,i,s),u.normalizeVec3(s),s}}();var f=function(){const e=u.vec3();return function(t){const i=Math.abs(t[0]);return i>Math.abs(t[1])&&i>Math.abs(t[2])?u.cross3Vec3(t,[0,1,0],e):u.cross3Vec3(t,[1,0,0],e),u.cross3Vec3(e,t,e),u.normalizeVec3(e),e}}();const g=function(){const t=u.vec3(),i=u.vec3(),s=u.vec4();return function(r,o,a){_(r,s);const n=f(s,o,a);v(o,n,t),v(a,n,i),u.subVec3(i,t);const l=u.dotVec3(i,s);e._pos[0]+=s[0]*l,e._pos[1]+=s[1]*l,e._pos[2]+=s[2]*l,e._rootNode.position=e._pos,e._sectionPlane&&(e._sectionPlane.pos=e._pos)}}();var m=function(){const t=u.vec4(),i=u.vec4(),s=u.vec4(),r=u.vec4();return function(o,a,n){if(_(o,r),!v(a,r,t)||!v(n,r,i)){const e=f(r,a,n);v(a,e,t,1),v(n,e,i,1);var l=u.dotVec3(t,r);t[0]-=l*r[0],t[1]-=l*r[1],t[2]-=l*r[2],l=u.dotVec3(i,r),i[0]-=l*r[0],i[1]-=l*r[1],i[2]-=l*r[2]}u.normalizeVec3(t),u.normalizeVec3(i),l=u.dotVec3(t,i),l=u.clamp(l,-1,1);var h=Math.acos(l)*u.RADTODEG;u.cross3Vec3(t,i,s),u.dotVec3(s,r)<0&&(h=-h),e._rootNode.rotate(o,h),b()}}(),v=function(){const t=u.vec4([0,0,0,1]),i=u.mat4();return function(s,r,o,a){a=a||0,t[0]=s[0]/h.width*2-1,t[1]=-(s[1]/h.height*2-1),t[2]=0,t[3]=1,u.mulMat4(c.projMatrix,c.viewMatrix,i),u.inverseMat4(i),u.transformVec4(i,t,t),u.mulVec4Scalar(t,1/t[3]);var n=c.eye;u.subVec4(t,n,t);const l=e._sectionPlane.pos;var d=-u.dotVec3(l,r)-a,p=u.dotVec3(r,t);if(Math.abs(p)>.005){var _=-(u.dotVec3(r,n)+d)/p;return u.mulVec3Scalar(t,_,o),u.addVec3(o,n),u.subVec3(o,l,o),!0}return!1}}();const b=function(){const t=u.vec3(),s=u.mat4();return function(){e.sectionPlane&&(u.quaternionToMat4(i.quaternion,s),u.transformVec3(s,[0,0,1],t),e._setSectionPlaneDir(t))}}();var P,y=!1;this._onCameraControlHover=this._viewer.cameraControl.on("hoverEnter",(e=>{if(this._visible&&!y){var i;switch(t=!1,P&&(P.visible=!1),e.entity.id){case this._displayMeshes.xAxisArrowHandle.id:case this._displayMeshes.xAxisHandle.id:i=this._affordanceMeshes.xAxisArrow,s=0;break;case this._displayMeshes.yAxisArrowHandle.id:case this._displayMeshes.yShaftHandle.id:i=this._affordanceMeshes.yAxisArrow,s=1;break;case this._displayMeshes.zAxisArrowHandle.id:case this._displayMeshes.zAxisHandle.id:i=this._affordanceMeshes.zAxisArrow,s=2;break;case this._displayMeshes.xCurveHandle.id:i=this._affordanceMeshes.xHoop,s=3;break;case this._displayMeshes.yCurveHandle.id:i=this._affordanceMeshes.yHoop,s=4;break;case this._displayMeshes.zCurveHandle.id:i=this._affordanceMeshes.zHoop,s=5;break;default:return void(s=-1)}i&&(i.visible=!0),P=i,t=!0}})),this._onCameraControlHoverLeave=this._viewer.cameraControl.on("hoverOut",(e=>{this._visible&&(P&&(P.visible=!1),P=null,s=-1)})),h.addEventListener("mousedown",this._canvasMouseDownListener=e=>{if(e.preventDefault(),this._visible&&t)switch(this._viewer.cameraControl.pointerEnabled=!1,e.which){case 1:y=!0;var i=p(e);r=s,o[0]=i[0],o[1]=i[1]}}),h.addEventListener("mousemove",this._canvasMouseMoveListener=e=>{if(!this._visible)return;if(!y)return;var t=p(e);const i=t[0],s=t[1];switch(r){case 0:g(a,o,t);break;case 1:g(n,o,t);break;case 2:g(l,o,t);break;case 3:m(a,o,t);break;case 4:m(n,o,t);break;case 5:m(l,o,t)}o[0]=i,o[1]=s}),h.addEventListener("mouseup",this._canvasMouseUpListener=e=>{this._visible&&(this._viewer.cameraControl.pointerEnabled=!0,y&&(e.which,y=!1,t=!1))}),h.addEventListener("wheel",this._canvasWheelListener=e=>{this._visible&&Math.max(-1,Math.min(1,40*-e.deltaY))})}_destroy(){this._unbindEvents(),this._destroyNodes()}_unbindEvents(){const e=this._viewer,t=e.scene,i=t.canvas.canvas,s=e.camera,r=e.cameraControl;t.off(this._onSceneTick),i.removeEventListener("mousedown",this._canvasMouseDownListener),i.removeEventListener("mousemove",this._canvasMouseMoveListener),i.removeEventListener("mouseup",this._canvasMouseUpListener),i.removeEventListener("wheel",this._canvasWheelListener),s.off(this._onCameraViewMatrix),s.off(this._onCameraProjMatrix),r.off(this._onCameraControlHover),r.off(this._onCameraControlHoverLeave)}_destroyNodes(){this._setSectionPlane(null),this._rootNode.destroy(),this._displayMeshes={},this._affordanceMeshes={}}}class Wo{constructor(e,t,i){this.id=i.id,this._sectionPlane=i,this._mesh=new ri(t,{id:i.id,geometry:new Ke(t,Ze({xSize:.5,ySize:.5,zSize:.001})),material:new et(t,{emissive:[1,1,1],diffuse:[0,0,0],backfaces:!1}),edgeMaterial:new rt(t,{edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),highlightMaterial:new it(t,{fill:!0,fillColor:[.5,1,.5],fillAlpha:.7,edges:!0,edgeColor:[0,0,0],edgeAlpha:1,edgeWidth:1}),selectedMaterial:new it(t,{fill:!0,fillColor:[0,0,1],fillAlpha:.7,edges:!0,edgeColor:[1,0,0],edgeAlpha:1,edgeWidth:1}),highlighted:!0,scale:[3,3,3],position:[0,0,0],rotation:[0,0,0],opacity:.3,edges:!0});{const e=u.vec3([0,0,0]),t=u.vec3(),i=u.vec3([0,0,1]),s=u.vec4(4),r=u.vec3(),o=()=>{const o=this._sectionPlane.scene.center,a=[-this._sectionPlane.dir[0],-this._sectionPlane.dir[1],-this._sectionPlane.dir[2]];u.subVec3(o,this._sectionPlane.pos,e);const n=-u.dotVec3(a,e);u.normalizeVec3(a),u.mulVec3Scalar(a,n,t);const l=u.vec3PairToQuaternion(i,this._sectionPlane.dir,s);r[0]=.1*t[0],r[1]=.1*t[1],r[2]=.1*t[2],this._mesh.quaternion=l,this._mesh.position=r};this._onSectionPlanePos=this._sectionPlane.on("pos",o),this._onSectionPlaneDir=this._sectionPlane.on("dir",o)}this._highlighted=!1,this._selected=!1}setHighlighted(e){this._highlighted=!!e,this._mesh.highlighted=this._highlighted,this._mesh.highlightMaterial.fillColor=e?[0,.7,0]:[0,0,0]}getHighlighted(){return this._highlighted}setSelected(e){this._selected=!!e,this._mesh.edgeMaterial.edgeWidth=e?3:1,this._mesh.highlightMaterial.edgeWidth=e?3:1}getSelected(){return this._selected}destroy(){this._sectionPlane.off(this._onSectionPlanePos),this._sectionPlane.off(this._onSectionPlaneDir),this._mesh.destroy()}}class Yo{constructor(e,t){if(!(t.onHoverEnterPlane&&t.onHoverLeavePlane&&t.onClickedNothing&&t.onClickedPlane))throw"Missing config(s): onHoverEnterPlane, onHoverLeavePlane, onClickedNothing || onClickedPlane";this.plugin=e,this._viewer=e.viewer,this._onHoverEnterPlane=t.onHoverEnterPlane,this._onHoverLeavePlane=t.onHoverLeavePlane,this._onClickedNothing=t.onClickedNothing,this._onClickedPlane=t.onClickedPlane,this._visible=!0,this._planes={},this._canvas=t.overviewCanvas,this._scene=new pt(this._viewer,{canvasId:this._canvas.id,transparent:!0}),this._scene.clearLights(),new Oe(this._scene,{dir:[.4,-.4,.8],color:[.8,1,1],intensity:1,space:"view"}),new Oe(this._scene,{dir:[-.8,-.3,-.4],color:[.8,.8,.8],intensity:1,space:"view"}),new Oe(this._scene,{dir:[.8,-.6,-.8],color:[1,1,1],intensity:1,space:"view"}),this._scene.camera,this._scene.camera.perspective.fov=70,this._zUp=!1;{const e=this._scene.camera,t=u.rotationMat4c(-90*u.DEGTORAD,1,0,0),i=u.vec3(),s=u.vec3(),r=u.vec3();this._synchCamera=()=>{const o=this._viewer.camera.eye,a=this._viewer.camera.look,n=this._viewer.camera.up;u.mulVec3Scalar(u.normalizeVec3(u.subVec3(o,a,i)),7),this._zUp?(u.transformVec3(t,i,s),u.transformVec3(t,n,r),e.look=[0,0,0],e.eye=u.transformVec3(t,i,s),e.up=u.transformPoint3(t,n,r)):(e.look=[0,0,0],e.eye=i,e.up=n)}}this._onViewerCameraMatrix=this._viewer.camera.on("matrix",this._synchCamera),this._onViewerCameraWorldAxis=this._viewer.camera.on("worldAxis",this._synchCamera),this._onViewerCameraFOV=this._viewer.camera.perspective.on("fov",(e=>{this._scene.camera.perspective.fov=e}));var i=null;this._onInputMouseMove=this._scene.input.on("mousemove",(e=>{const t=this._scene.pick({canvasPos:e});t?i&&t.entity.id===i.id||(i&&this._planes[i.id]&&this._onHoverLeavePlane(i.id),i=t.entity,this._planes[i.id]&&this._onHoverEnterPlane(i.id)):i&&(this._onHoverLeavePlane(i.id),i=null)})),this._scene.canvas.canvas.addEventListener("mouseup",this._onCanvasMouseUp=()=>{i?this._planes[i.id]&&this._onClickedPlane(i.id):this._onClickedNothing()}),this._scene.canvas.canvas.addEventListener("mouseout",this._onCanvasMouseOut=()=>{i&&(this._onHoverLeavePlane(i.id),i=null)}),this.setVisible(t.overviewVisible)}addSectionPlane(e){this._planes[e.id]=new Wo(this,this._scene,e)}setPlaneHighlighted(e,t){const i=this._planes[e];i&&i.setHighlighted(t)}setPlaneSelected(e,t){const i=this._planes[e];i&&i.setSelected(t)}removeSectionPlane(e){const t=this._planes[e.id];t&&(t.destroy(),delete this._planes[e.id])}setVisible(e=!0){this._visible=e,this._canvas.style.visibility=e?"visible":"hidden"}getVisible(){return this._visible}destroy(){this._viewer.camera.off(this._onViewerCameraMatrix),this._viewer.camera.off(this._onViewerCameraWorldAxis),this._viewer.camera.perspective.off(this._onViewerCameraFOV),this._scene.input.off(this._onInputMouseMove),this._scene.canvas.canvas.removeEventListener("mouseup",this._onCanvasMouseUp),this._scene.canvas.canvas.removeEventListener("mouseout",this._onCanvasMouseOut),this._scene.destroy()}}const qo=u.AABB3(),Ko=u.vec3();class Zo extends a{constructor(e,t={}){if(super("SectionPlanes",e),this._freeControls=[],this._sectionPlanes=e.scene.sectionPlanes,this._controls={},this._shownControlId=null,null!==t.overviewCanvasId&&void 0!==t.overviewCanvasId){const e=document.getElementById(t.overviewCanvasId);e?this._overview=new Yo(this,{overviewCanvas:e,visible:t.overviewVisible,onHoverEnterPlane:e=>{this._overview.setPlaneHighlighted(e,!0)},onHoverLeavePlane:e=>{this._overview.setPlaneHighlighted(e,!1)},onClickedPlane:e=>{if(this.getShownControl()===e)return void this.hideControl();this.showControl(e);const t=this.sectionPlanes[e].pos;qo.set(this.viewer.scene.aabb),u.getAABB3Center(qo,Ko),qo[0]+=t[0]-Ko[0],qo[1]+=t[1]-Ko[1],qo[2]+=t[2]-Ko[2],qo[3]+=t[0]-Ko[0],qo[4]+=t[1]-Ko[1],qo[5]+=t[2]-Ko[2],this.viewer.cameraFlight.flyTo({aabb:qo,fitFOV:65})},onClickedNothing:()=>{this.hideControl()}}):this.warn("Can't find overview canvas: '"+t.overviewCanvasId+"' - will create plugin without overview")}this._onSceneSectionPlaneCreated=e.scene.on("sectionPlaneCreated",(e=>{this._sectionPlaneCreated(e)}))}setOverviewVisible(e){this._overview&&this._overview.setVisible(e)}getOverviewVisible(){if(this._overview)return this._overview.getVisible()}get sectionPlanes(){return this._sectionPlanes}createSectionPlane(e={}){return void 0!==e.id&&null!==e.id&&this.viewer.scene.components[e.id]&&(this.error("Viewer component with this ID already exists: "+e.id),delete e.id),new li(this.viewer.scene,{id:e.id,pos:e.pos,dir:e.dir,active:!0})}_sectionPlaneCreated(e){const t=this._freeControls.length>0?this._freeControls.pop():new Ho(this);t._setSectionPlane(e),t.setVisible(!1),this._controls[e.id]=t,this._overview&&this._overview.addSectionPlane(e),e.once("destroyed",(()=>{this._sectionPlaneDestroyed(e)}))}flipSectionPlanes(){const e=this.viewer.scene.sectionPlanes;for(let t in e)e[t].flipDir()}showControl(e){const t=this._controls[e];t?(this.hideControl(),t.setVisible(!0),this._overview&&this._overview.setPlaneSelected(e,!0),this._shownControlId=e):this.error("Control not found: "+e)}getShownControl(){return this._shownControlId}hideControl(){for(var e in this._controls)this._controls.hasOwnProperty(e)&&(this._controls[e].setVisible(!1),this._overview&&this._overview.setPlaneSelected(e,!1));this._shownControlId=null}destroySectionPlane(e){var t=this.viewer.scene.sectionPlanes[e];t?(this._sectionPlaneDestroyed(t),t.destroy(),e===this._shownControlId&&(this._shownControlId=null)):this.error("SectionPlane not found: "+e)}_sectionPlaneDestroyed(e){this._overview&&this._overview.removeSectionPlane(e);const t=this._controls[e.id];t&&(t.setVisible(!1),t._setSectionPlane(null),delete this._controls[e.id],this._freeControls.push(t))}clear(){const e=Object.keys(this._sectionPlanes);for(var t=0,i=e.length;t<i;t++)this.destroySectionPlane(e[t])}send(e,t){switch(e){case"snapshotStarting":for(let e in this._controls)this._controls.hasOwnProperty(e)&&this._controls[e].setCulled(!0);break;case"snapshotFinished":for(let e in this._controls)this._controls.hasOwnProperty(e)&&this._controls[e].setCulled(!1);break;case"clearSectionPlanes":this.clear()}}destroy(){this.clear(),this._overview&&this._overview.destroy(),this._destroyFreeControls(),super.destroy()}_destroyFreeControls(){for(var e=this._freeControls.pop();e;)e._destroy(),e=this._freeControls.pop();this.viewer.scene.off(this._onSceneSectionPlaneCreated)}}u.vec3(),u.vec3(),u.vec3(),u.mat4();function Qo(e,t){const i=e.rootMetaObject;return i?$o(i,t):(t.push("Can't build storeys hierarchy: model is empty"),!1)}function $o(e,t,i=0,s,r){s=s||{foundIFCBuildingStoreys:!1};const o=e.type,a=e.children;if("IfcBuilding"===o)r=!0;else if("IfcBuildingStorey"===o){if(!r)return t.push("Can't build storeys hierarchy: IfcBuildingStorey found without parent IfcBuilding"),!1;s.foundIFCBuildingStoreys=!0}if(a)for(let e=0,o=a.length;e<o;e++)if(!$o(a[e],t,i+1,s,r))return!1;return 0===i&&s.foundIFCBuildingStoreys,!0}const Jo=new e;class ea{constructor(e,t,i,s,r){if(!r.containerElement)throw"Config expected: containerElement";const o=s.rootMetaObject;o&&(this.errors=[],this.valid=!0,this.metaModel=s,this._id=Jo.addItem(),this._baseId=""+this._id,this._viewer=e,this._treeViewPlugin=t,this._rootMetaObject=o,this._containerElement=r.containerElement,this._rootElement=null,this._muteSceneEvents=!1,this._muteTreeEvents=!1,this._rootNodes=[],this._objectNodes={},this._rootName=r.rootName,this._sortNodes=r.sortNodes,this._pruneEmptyNodes=r.pruneEmptyNodes,this._showListItemElementId=null,this._containerElement.oncontextmenu=e=>{e.preventDefault()},this._onObjectVisibility=this._viewer.scene.on("objectVisibility",(e=>{if(this._muteSceneEvents)return;const t=e.id,i=this._objectNodes[t];if(!i)return;const s=e.visible;if(s===i.checked)return;this._muteTreeEvents=!0,i.checked=s,s?i.numVisibleEntities++:i.numVisibleEntities--;const r=document.getElementById(i.nodeId);r&&(r.checked=s);let o=i.parent;for(;o;){o.checked=s,s?o.numVisibleEntities++:o.numVisibleEntities--;const e=document.getElementById(o.nodeId);if(e){const t=o.numVisibleEntities>0;t!==e.checked&&(e.checked=t)}o=o.parent}this._muteTreeEvents=!1})),this.switchExpandHandler=e=>{e.preventDefault(),e.stopPropagation();const t=e.target;this._expandSwitchElement(t)},this.switchCollapseHandler=e=>{e.preventDefault(),e.stopPropagation();const t=e.target;this._collapseSwitchElement(t)},this._checkboxChangeHandler=e=>{if(this._muteTreeEvents)return;this._muteSceneEvents=!0;const t=e.target,i=t.checked,s=t.id,r=this._nodeToObjectID(s),o=this._objectNodes[r],a=this._viewer.scene.objects;let n=0;this._withNodeTree(o,(e=>{const t=e.objectId,s=e.nodeId,r=a[t],o=0===e.children.length;e.numVisibleEntities=i?e.numEntities:0,o&&i!==e.checked&&n++,e.checked=i;const l=document.getElementById(s);l&&(l.checked=i),r&&(r.visible=i)}));let l=o.parent;for(;l;){l.checked=i;const e=document.getElementById(l.nodeId);i?l.numVisibleEntities+=n:l.numVisibleEntities-=n;const t=l.numVisibleEntities>0;t!==e.checked&&(e.checked=t),l=l.parent}this._muteSceneEvents=!1},this._hierarchy=r.hierarchy||"containment",this._autoExpandDepth=r.autoExpandDepth||0,this._createNodes())}_nodeToObjectID(e){return e.substring(this._baseId.length)}_objectToNodeID(e){return this._baseId+e}setAutoExpandDepth(e=0){this._autoExpandDepth=e}setHierarchy(e){this._hierarchy!==e&&(this._hierarchy=e,this._createNodes())}_createNodes(){this._rootElement&&(this._rootElement.parentNode.removeChild(this._rootElement),this._rootElement=null),this._rootNodes=[],this._objectNodes={},this._validate(),this.valid?this._createEnabledNodes():this._createDisabledNodes()}_validate(){switch(this.errors=[],this._hierarchy){case"storeys":this.valid=Qo(this.metaModel,this.errors);break;case"types":this.valid=(e=this.metaModel,t=this.errors,!!e.rootMetaObject||(t.push("Can't build types hierarchy: model is empty"),!1));break;case"containment":default:this.valid=function(e,t){return!!e.rootMetaObject||(t.push("Can't build containment hierarchy: model is empty"),!1)}(this.metaModel,this.errors)}var e,t;return this.valid}_createEnabledNodes(){switch(this._pruneEmptyNodes&&this._findEmptyNodes(),this._hierarchy){case"storeys":this._createStoreysNodes(),0===this._rootNodes.length&&this._treeViewPlugin.error("Failed to build storeys hierarchy for model '"+this.metaModel.id+"' - perhaps this model is not an IFC model?");break;case"types":this._createTypesNodes();break;case"containment":default:this._createContainmentNodes()}this._sortNodes&&this._doSortNodes(),this._synchNodesToEntities(),this._createTrees(),this.expandToDepth(this._autoExpandDepth)}_createDisabledNodes(){const e=this._rootMetaObject,t=e.type,i=e.name,s=i&&""!==i&&"Undefined"!==i&&"Default"!==i?i:t,r=document.createElement("ul"),o=document.createElement("li");r.appendChild(o),this._containerElement.appendChild(r),this._rootElement=r;const a=document.createElement("a");a.href="#",a.textContent="!",a.classList.add("warn"),a.classList.add("warning"),o.appendChild(a);const n=document.createElement("span");n.textContent=s,o.appendChild(n)}_findEmptyNodes(e=this._rootMetaObject,t=0){const i=this._treeViewPlugin.viewer.scene,s=e.children,r=e.id,o=i.objects[r];if(e._countEntities=0,o&&e._countEntities++,s)for(let t=0,i=s.length;t<i;t++){const i=s[t];i._countEntities=this._findEmptyNodes(i),e._countEntities+=i._countEntities}return e._countEntities}_createStoreysNodes(e=this._rootMetaObject,t,i,s){if(this._pruneEmptyNodes&&0===e._countEntities)return;const r=e.type,o=e.name,a=e.children,n=e.id;if("IfcBuilding"===r)t={nodeId:this._objectToNodeID(n),objectId:n,title:this._rootName||(o&&""!==o&&"Undefined"!==o&&"Default"!==o?o:r),type:r,parent:null,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},this._rootNodes.push(t),this._objectNodes[t.objectId]=t;else if("IfcBuildingStorey"===r){if(!t)return void this._treeViewPlugin.error("Failed to build storeys hierarchy for model '"+this.metaModel.id+"' - model does not have an IfcBuilding object, or is not an IFC model");i={nodeId:this._objectToNodeID(n),objectId:n,title:o&&""!==o&&"Undefined"!==o&&"Default"!==o?o:r,type:r,parent:t,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},t.children.push(i),this._objectNodes[i.objectId]=i,s={}}else if(i&&this._viewer.scene.objects[n]){let e=(s=s||{})[r];if(!e){const t=i.objectId+"."+r;e={nodeId:this._objectToNodeID(t),objectId:t,title:r,type:r,parent:i,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},i.children.push(e),this._objectNodes[t]=e,s[r]=e}const t={nodeId:this._objectToNodeID(n),objectId:n,title:o&&""!==o&&"Undefined"!==o&&"Default"!==o?o:r,type:r,parent:e,numEntities:0,numVisibleEntities:0,checked:!1,children:[]};e.children.push(t),this._objectNodes[t.objectId]=t}if(a)for(let e=0,r=a.length;e<r;e++){const r=a[e];this._createStoreysNodes(r,t,i,s)}}_createTypesNodes(e=this._rootMetaObject,t,i){if(this._pruneEmptyNodes&&0===e._countEntities)return;const s=e.type,r=e.name,o=e.children,a=e.id;if(e.id===this._rootMetaObject.id)t={nodeId:this._objectToNodeID(a),objectId:a,title:this._rootName||(r&&""!==r&&"Undefined"!==r&&"Default"!==r?r:s),type:s,parent:null,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},this._rootNodes.push(t),this._objectNodes[t.objectId]=t,i={};else if(t&&this._viewer.scene.objects[a]){let e=i[s];e||(e={nodeId:this._objectToNodeID(t.objectId+"."+s),objectId:t.objectId+"."+s,title:s,type:s,parent:t,numEntities:0,numVisibleEntities:0,checked:!1,children:[]},t.children.push(e),this._objectNodes[e.objectId]=e,i[s]=e);const o={nodeId:this._objectToNodeID(a),objectId:a,title:r&&""!==r&&"Default"!==r?r:s,type:s,parent:e,numEntities:0,numVisibleEntities:0,checked:!1,children:[]};e.children.push(o),this._objectNodes[o.objectId]=o}if(o)for(let e=0,s=o.length;e<s;e++){const s=o[e];this._createTypesNodes(s,t,i)}}_createContainmentNodes(e=this._rootMetaObject,t){if(this._pruneEmptyNodes&&0===e._countEntities)return;const i=e.type,s=e.name||i,r=e.children,o=e.id,a={nodeId:this._objectToNodeID(o),objectId:o,title:t?s&&""!==s&&"Undefined"!==s&&"Default"!==s?s:i:this._rootName||s,type:i,parent:t,numEntities:0,numVisibleEntities:0,checked:!1,children:[]};if(t?t.children.push(a):this._rootNodes.push(a),this._objectNodes[a.objectId]=a,r)for(let e=0,t=r.length;e<t;e++){const t=r[e];this._createContainmentNodes(t,a)}}_doSortNodes(){for(let e=0,t=this._rootNodes.length;e<t;e++){const t=this._rootNodes[e];this._sortChildren(t)}}_sortChildren(e){const t=e.children;if(t&&0!==t.length){"storeys"===this._hierarchy&&"IfcBuilding"===e.type?t.sort(this._getSpatialSortFunc()):t.sort(this._alphaSortFunc);for(let e=0,i=t.length;e<i;e++){const i=t[e];this._sortChildren(i)}}}_getSpatialSortFunc(){const e=this._treeViewPlugin.viewer,t=e.scene,i=t.camera,s=e.metaScene;return this._spatialSortFunc||(this._spatialSortFunc=(e,r)=>{e.aabb&&r.aabb||(e.aabb||(e.aabb=t.getAABB(s.getObjectIDsInSubtree(e.objectId))),r.aabb||(r.aabb=t.getAABB(s.getObjectIDsInSubtree(r.objectId))));let o=0;return o=i.xUp?0:i.yUp?1:2,e.aabb[o]>r.aabb[o]?-1:e.aabb[o]<r.aabb[o]?1:0})}_alphaSortFunc(e,t){const i=e.title.toUpperCase(),s=t.title.toUpperCase();return i<s?-1:i>s?1:0}_synchNodesToEntities(){const e=this._rootMetaObject.getObjectIDsInSubtree(),t=this._viewer.metaScene.metaObjects,i=this._viewer.scene.objects;for(let s=0,r=e.length;s<r;s++){const r=e[s];if(t[r]){const e=this._objectNodes[r];if(e){const t=i[r];if(t){const i=t.visible;e.numEntities=1,i?(e.numVisibleEntities=1,e.checked=!0):(e.numVisibleEntities=0,e.checked=!1);let s=e.parent;for(;s;)s.numEntities++,i&&(s.numVisibleEntities++,s.checked=!0),s=s.parent}}}}}_withNodeTree(e,t){t(e);const i=e.children;if(i)for(let e=0,s=i.length;e<s;e++)this._withNodeTree(i[e],t)}_createTrees(){if(0===this._rootNodes.length)return;const e=this._rootNodes.map((e=>this._createNodeElement(e))),t=document.createElement("ul");e.forEach((e=>{t.appendChild(e)})),this._containerElement.appendChild(t),this._rootElement=t}_createNodeElement(e){const t=document.createElement("li"),i=e.nodeId;if(t.id="node-"+i,e.children.length>0){const e="switch-"+i,s=document.createElement("a");s.href="#",s.id=e,s.textContent="+",s.classList.add("plus"),s.addEventListener("click",this.switchExpandHandler),t.appendChild(s)}const s=document.createElement("input");s.id=i,s.type="checkbox",s.checked=e.checked,s.style["pointer-events"]="all",s.addEventListener("change",this._checkboxChangeHandler),t.appendChild(s);const r=document.createElement("span");return r.textContent=e.title,t.appendChild(r),r.oncontextmenu=t=>{this._treeViewPlugin.fire("contextmenu",{event:t,viewer:this._viewer,treeViewPlugin:this._treeViewPlugin,treeViewNode:e}),t.preventDefault()},r.onclick=t=>{this._treeViewPlugin.fire("nodeTitleClicked",{event:t,viewer:this._viewer,treeViewPlugin:this._treeViewPlugin,treeViewNode:e}),t.preventDefault()},t}expandToDepth(e){const t=(i,s)=>{if(s===e)return;const r="switch-"+i.nodeId,o=document.getElementById(r);if(o){this._expandSwitchElement(o);const e=i.children;for(var a=0,n=e.length;a<n;a++){const i=e[a];t(i,s+1)}}};for(let e=0,i=this._rootNodes.length;e<i;e++){const i=this._rootNodes[e];t(i,0)}}collapse(){for(let e=0,t=this._rootNodes.length;e<t;e++){const t=this._rootNodes[e].objectId;this._collapseNode(t)}}showNode(e){this._showListItemElementId&&this.unShowNode();const t=this._objectNodes[e];if(!t)return;const i=t.nodeId,s="switch-"+i,r=document.getElementById(s);if(r)return this._expandSwitchElement(r),void r.scrollIntoView();const o=[];o.unshift(t);let a=t.parent;for(;a;)o.unshift(a),a=a.parent;for(let e=0,t=o.length;e<t;e++){const t="switch-"+o[e].nodeId,i=document.getElementById(t);i&&this._expandSwitchElement(i)}const n="node-"+i,l=document.getElementById(n);l.scrollIntoView({block:"center"}),l.classList.add("highlighted-node"),this._showListItemElementId=n}unShowNode(){if(!this._showListItemElementId)return;const e=document.getElementById(this._showListItemElementId);e?(e.classList.remove("highlighted-node"),this._showListItemElementId=null):this._showListItemElementId=null}_expandSwitchElement(e){const t=e.parentElement;if(t.getElementsByTagName("li")[0])return;const i=t.id.replace("node-",""),s=this._nodeToObjectID(i),r=this._objectNodes[s].children.map((e=>this._createNodeElement(e))),o=document.createElement("ul");r.forEach((e=>{o.appendChild(e)})),t.appendChild(o),e.classList.remove("plus"),e.classList.add("minus"),e.textContent="-",e.removeEventListener("click",this.switchExpandHandler),e.addEventListener("click",this.switchCollapseHandler)}_collapseNode(e){const t="switch-"+this._objectToNodeID(e),i=document.getElementById(t);this._collapseSwitchElement(i)}_collapseSwitchElement(e){if(!e)return;const t=e.parentElement;if(!t)return;const i=t.querySelector("ul");i&&(t.removeChild(i),e.classList.remove("minus"),e.classList.add("plus"),e.textContent="+",e.removeEventListener("click",this.switchCollapseHandler),e.addEventListener("click",this.switchExpandHandler))}destroy(){this._rootElement&&!this._destroyed&&(this._rootElement.parentNode.removeChild(this._rootElement),this._viewer.scene.off(this._onObjectVisibility),this._destroyed=!0,Jo.removeItem(this._id))}}class ta extends a{constructor(e,t={}){if(super("TreeViewPlugin",e),t.containerElement){if(this._containerElement=t.containerElement,this._modelTreeViews={},this._autoAddModels=!1!==t.autoAddModels,this._autoExpandDepth=t.autoExpandDepth||0,this._sortNodes=!1!==t.sortNodes,this._pruneEmptyNodes=!1!==t.pruneEmptyNodes,this._autoAddModels){const e=Object.keys(this.viewer.metaScene.metaModels);for(let t=0,i=e.length;t<i;t++){const i=e[t];this.addModel(i)}this.viewer.scene.on("modelLoaded",(e=>{this.viewer.metaScene.metaModels[e]&&this.addModel(e)}))}this.hierarchy=t.hierarchy}else this.error("Config expected: containerElement")}get modelTreeViews(){return this._modelTreeViews}set hierarchy(e){"containment"!==(e=e||"containment")&&"storeys"!==e&&"types"!==e&&(this.error("Unsupported value for `hierarchy' - defaulting to 'containment'"),e="containment"),this._hierarchy=e;for(let e in this._modelTreeViews)this._modelTreeViews.hasOwnProperty(e)&&this._modelTreeViews[e].setHierarchy(this._hierarchy)}get hierarchy(){return this._hierarchy}addModel(e,t={}){if(!this._containerElement)return;const i=this.viewer.scene.models[e];if(!i)throw"Model not found: "+e;const s=this.viewer.metaScene.metaModels[e];if(!s)return void this.error("MetaModel not found: "+e);if(this._modelTreeViews[e])return void this.warn("Model already added: "+e);const r=new ea(this.viewer,this,i,s,{containerElement:this._containerElement,autoExpandDepth:this._autoExpandDepth,hierarchy:this._hierarchy,sortNodes:this._sortNodes,pruneEmptyNodes:this._pruneEmptyNodes,rootName:t.rootName});return this._modelTreeViews[e]=r,i.on("destroyed",(()=>{this.removeModel(i.id)})),r}removeModel(e){if(!this._containerElement)return;const t=this._modelTreeViews[e];t?(t.destroy(),delete this._modelTreeViews[e]):this.warn("Model not added: "+e)}collapse(){for(let e in this._modelTreeViews)this._modelTreeViews.hasOwnProperty(e)&&this._modelTreeViews[e].collapse()}showNode(e){this.unShowNode();const t=this.viewer.metaScene.metaObjects[e];if(!t)return void this.error("MetaObject not found: "+e);const i=t.metaModel.id,s=this._modelTreeViews[i];s?s.showNode(e):this.error("Object not in this TreeView: "+e)}unShowNode(){for(let e in this._modelTreeViews)this._modelTreeViews.hasOwnProperty(e)&&this._modelTreeViews[e].unShowNode()}expandToDepth(e){for(let t in this._modelTreeViews)if(this._modelTreeViews.hasOwnProperty(t)){const i=this._modelTreeViews[t];i.collapse(),i.expandToDepth(e)}}withNodeTree(e,t){t(e);const i=e.children;if(i)for(let e=0,s=i.length;e<s;e++)this.withNodeTree(i[e],t)}destroy(){if(this._containerElement){for(let e in this._modelTreeViews)this._modelTreeViews.hasOwnProperty(e)&&this._modelTreeViews[e].destroy();this._modelTreeViews={},super.destroy()}}}u.vec3(),u.vec3(),u.mat4();class ia{constructor(){}getMetaModel(e,t,i){f.loadJSON(e,(e=>{t(e)}),(function(e){i(e)}))}getXKT(e,t,i){var s=()=>{};t=t||s,i=i||s;const r=e.match(/^data:(.*?)(;base64)?,(.*)$/);if(r){const s=!!r[2];var o=r[3];o=window.decodeURIComponent(o),s&&(o=window.atob(o));try{const e=new ArrayBuffer(o.length),i=new Uint8Array(e);for(var a=0;a<o.length;a++)i[a]=o.charCodeAt(a);t(e)}catch(e){i(e)}}else{const s=new XMLHttpRequest;s.open("GET",e,!0),s.responseType="arraybuffer",s.onreadystatechange=function(){4===s.readyState&&(200===s.status?t(s.response):i("getXKT error : "+s.response))},s.send(null)}}}!function(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).pako=e()}((function(){return function e(t,i,s){function r(a,n){if(!i[a]){if(!t[a]){var l="function"==typeof require&&require;if(!n&&l)return l(a,!0);if(o)return o(a,!0);var h=new Error("Cannot find module '"+a+"'");throw h.code="MODULE_NOT_FOUND",h}var c=i[a]={exports:{}};t[a][0].call(c.exports,(function(e){return r(t[a][1][e]||e)}),c,c.exports,e,t,i,s)}return i[a].exports}for(var o="function"==typeof require&&require,a=0;a<s.length;a++)r(s[a]);return r}({1:[function(e,t,i){var s=e("./zlib/deflate"),r=e("./utils/common"),o=e("./utils/strings"),a=e("./zlib/messages"),n=e("./zlib/zstream"),l=Object.prototype.toString;function h(e){if(!(this instanceof h))return new h(e);this.options=r.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new n,this.strm.avail_out=0;var i=s.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(0!==i)throw new Error(a[i]);if(t.header&&s.deflateSetHeader(this.strm,t.header),t.dictionary){var c;if(c="string"==typeof t.dictionary?o.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,0!==(i=s.deflateSetDictionary(this.strm,c)))throw new Error(a[i]);this._dict_set=!0}}function c(e,t){var i=new h(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}h.prototype.push=function(e,t){var i,a,n=this.strm,h=this.options.chunkSize;if(this.ended)return!1;a=t===~~t?t:!0===t?4:0,"string"==typeof e?n.input=o.string2buf(e):"[object ArrayBuffer]"===l.call(e)?n.input=new Uint8Array(e):n.input=e,n.next_in=0,n.avail_in=n.input.length;do{if(0===n.avail_out&&(n.output=new r.Buf8(h),n.next_out=0,n.avail_out=h),1!==(i=s.deflate(n,a))&&0!==i)return this.onEnd(i),this.ended=!0,!1;0!==n.avail_out&&(0!==n.avail_in||4!==a&&2!==a)||("string"===this.options.to?this.onData(o.buf2binstring(r.shrinkBuf(n.output,n.next_out))):this.onData(r.shrinkBuf(n.output,n.next_out)))}while((n.avail_in>0||0===n.avail_out)&&1!==i);return 4===a?(i=s.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,0===i):2!==a||(this.onEnd(0),n.avail_out=0,!0)},h.prototype.onData=function(e){this.chunks.push(e)},h.prototype.onEnd=function(e){0===e&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Deflate=h,i.deflate=c,i.deflateRaw=function(e,t){return(t=t||{}).raw=!0,c(e,t)},i.gzip=function(e,t){return(t=t||{}).gzip=!0,c(e,t)}},{"./utils/common":3,"./utils/strings":4,"./zlib/deflate":8,"./zlib/messages":13,"./zlib/zstream":15}],2:[function(e,t,i){var s=e("./zlib/inflate"),r=e("./utils/common"),o=e("./utils/strings"),a=e("./zlib/constants"),n=e("./zlib/messages"),l=e("./zlib/zstream"),h=e("./zlib/gzheader"),c=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=r.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&0==(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=s.inflateInit2(this.strm,t.windowBits);if(i!==a.Z_OK)throw new Error(n[i]);if(this.header=new h,s.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===c.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=s.inflateSetDictionary(this.strm,t.dictionary))!==a.Z_OK))throw new Error(n[i])}function d(e,t){var i=new u(t);if(i.push(e,!0),i.err)throw i.msg||n[i.err];return i.result}u.prototype.push=function(e,t){var i,n,l,h,u,d=this.strm,p=this.options.chunkSize,_=this.options.dictionary,f=!1;if(this.ended)return!1;n=t===~~t?t:!0===t?a.Z_FINISH:a.Z_NO_FLUSH,"string"==typeof e?d.input=o.binstring2buf(e):"[object ArrayBuffer]"===c.call(e)?d.input=new Uint8Array(e):d.input=e,d.next_in=0,d.avail_in=d.input.length;do{if(0===d.avail_out&&(d.output=new r.Buf8(p),d.next_out=0,d.avail_out=p),(i=s.inflate(d,a.Z_NO_FLUSH))===a.Z_NEED_DICT&&_&&(i=s.inflateSetDictionary(this.strm,_)),i===a.Z_BUF_ERROR&&!0===f&&(i=a.Z_OK,f=!1),i!==a.Z_STREAM_END&&i!==a.Z_OK)return this.onEnd(i),this.ended=!0,!1;d.next_out&&(0!==d.avail_out&&i!==a.Z_STREAM_END&&(0!==d.avail_in||n!==a.Z_FINISH&&n!==a.Z_SYNC_FLUSH)||("string"===this.options.to?(l=o.utf8border(d.output,d.next_out),h=d.next_out-l,u=o.buf2string(d.output,l),d.next_out=h,d.avail_out=p-h,h&&r.arraySet(d.output,d.output,l,h,0),this.onData(u)):this.onData(r.shrinkBuf(d.output,d.next_out)))),0===d.avail_in&&0===d.avail_out&&(f=!0)}while((d.avail_in>0||0===d.avail_out)&&i!==a.Z_STREAM_END);return i===a.Z_STREAM_END&&(n=a.Z_FINISH),n===a.Z_FINISH?(i=s.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===a.Z_OK):n!==a.Z_SYNC_FLUSH||(this.onEnd(a.Z_OK),d.avail_out=0,!0)},u.prototype.onData=function(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===a.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=u,i.inflate=d,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},i.ungzip=d},{"./utils/common":3,"./utils/strings":4,"./zlib/constants":6,"./zlib/gzheader":9,"./zlib/inflate":11,"./zlib/messages":13,"./zlib/zstream":15}],3:[function(e,t,i){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var s in i)r(i,s)&&(e[s]=i[s])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var o={arraySet:function(e,t,i,s,r){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+s),r);else for(var o=0;o<s;o++)e[r+o]=t[i+o]},flattenChunks:function(e){var t,i,s,r,o,a;for(s=0,t=0,i=e.length;t<i;t++)s+=e[t].length;for(a=new Uint8Array(s),r=0,t=0,i=e.length;t<i;t++)o=e[t],a.set(o,r),r+=o.length;return a}},a={arraySet:function(e,t,i,s,r){for(var o=0;o<s;o++)e[r+o]=t[i+o]},flattenChunks:function(e){return[].concat.apply([],e)}};i.setTyped=function(e){e?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,o)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,a))},i.setTyped(s)},{}],4:[function(e,t,i){var s=e("./common"),r=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var a=new s.Buf8(256),n=0;n<256;n++)a[n]=n>=252?6:n>=248?5:n>=240?4:n>=224?3:n>=192?2:1;function l(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&r))return String.fromCharCode.apply(null,s.shrinkBuf(e,t));for(var i="",a=0;a<t;a++)i+=String.fromCharCode(e[a]);return i}a[254]=a[254]=1,i.string2buf=function(e){var t,i,r,o,a,n=e.length,l=0;for(o=0;o<n;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<n&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=new s.Buf8(l),a=0,o=0;a<l;o++)55296==(64512&(i=e.charCodeAt(o)))&&o+1<n&&56320==(64512&(r=e.charCodeAt(o+1)))&&(i=65536+(i-55296<<10)+(r-56320),o++),i<128?t[a++]=i:i<2048?(t[a++]=192|i>>>6,t[a++]=128|63&i):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|63&i):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|63&i);return t},i.buf2binstring=function(e){return l(e,e.length)},i.binstring2buf=function(e){for(var t=new s.Buf8(e.length),i=0,r=t.length;i<r;i++)t[i]=e.charCodeAt(i);return t},i.buf2string=function(e,t){var i,s,r,o,n=t||e.length,h=new Array(2*n);for(s=0,i=0;i<n;)if((r=e[i++])<128)h[s++]=r;else if((o=a[r])>4)h[s++]=65533,i+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&i<n;)r=r<<6|63&e[i++],o--;o>1?h[s++]=65533:r<65536?h[s++]=r:(r-=65536,h[s++]=55296|r>>10&1023,h[s++]=56320|1023&r)}return l(h,s)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+a[e[i]]>t?i:t}},{"./common":3}],5:[function(e,t,i){t.exports=function(e,t,i,s){for(var r=65535&e|0,o=e>>>16&65535|0,a=0;0!==i;){i-=a=i>2e3?2e3:i;do{o=o+(r=r+t[s++]|0)|0}while(--a);r%=65521,o%=65521}return r|o<<16|0}},{}],6:[function(e,t,i){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],7:[function(e,t,i){var s=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var s=0;s<8;s++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,r){var o=s,a=r+i;e^=-1;for(var n=r;n<a;n++)e=e>>>8^o[255&(e^t[n])];return-1^e}},{}],8:[function(e,t,i){var s,r=e("../utils/common"),o=e("./trees"),a=e("./adler32"),n=e("./crc32"),l=e("./messages"),h=-2,c=258,u=262,d=103,p=113,_=666;function f(e,t){return e.msg=l[t],t}function g(e){return(e<<1)-(e>4?9:0)}function m(e){for(var t=e.length;--t>=0;)e[t]=0}function v(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(r.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function b(e,t){o._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,v(e.strm)}function P(e,t){e.pending_buf[e.pending++]=t}function y(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function M(e,t){var i,s,r=e.max_chain_length,o=e.strstart,a=e.prev_length,n=e.nice_match,l=e.strstart>e.w_size-u?e.strstart-(e.w_size-u):0,h=e.window,d=e.w_mask,p=e.prev,_=e.strstart+c,f=h[o+a-1],g=h[o+a];e.prev_length>=e.good_match&&(r>>=2),n>e.lookahead&&(n=e.lookahead);do{if(h[(i=t)+a]===g&&h[i+a-1]===f&&h[i]===h[o]&&h[++i]===h[o+1]){o+=2,i++;do{}while(h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&h[++o]===h[++i]&&o<_);if(s=c-(_-o),o=_-c,s>a){if(e.match_start=t,a=s,s>=n)break;f=h[o+a-1],g=h[o+a]}}}while((t=p[t&d])>l&&0!=--r);return a<=e.lookahead?a:e.lookahead}function x(e){var t,i,s,o,l,h,c,d,p,_,f=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-u)){r.arraySet(e.window,e.window,f,f,0),e.match_start-=f,e.strstart-=f,e.block_start-=f,t=i=e.hash_size;do{s=e.head[--t],e.head[t]=s>=f?s-f:0}while(--i);t=i=f;do{s=e.prev[--t],e.prev[t]=s>=f?s-f:0}while(--i);o+=f}if(0===e.strm.avail_in)break;if(h=e.strm,c=e.window,d=e.strstart+e.lookahead,p=o,_=void 0,(_=h.avail_in)>p&&(_=p),i=0===_?0:(h.avail_in-=_,r.arraySet(c,h.input,h.next_in,_,d),1===h.state.wrap?h.adler=a(h.adler,c,_,d):2===h.state.wrap&&(h.adler=n(h.adler,c,_,d)),h.next_in+=_,h.total_in+=_,_),e.lookahead+=i,e.lookahead+e.insert>=3)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+3-1])&e.hash_mask,e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead<u&&0!==e.strm.avail_in)}function w(e,t){for(var i,s;;){if(e.lookahead<u){if(x(e),e.lookahead<u&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-u&&(e.match_length=M(e,i)),e.match_length>=3)if(s=o._tr_tally(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!=--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else s=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(s&&(b(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,4===t?(b(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(b(e,!1),0===e.strm.avail_out)?1:2}function E(e,t){for(var i,s,r;;){if(e.lookahead<u){if(x(e),e.lookahead<u&&0===t)return 1;if(0===e.lookahead)break}if(i=0,e.lookahead>=3&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-u&&(e.match_length=M(e,i),e.match_length<=5&&(1===e.strategy||3===e.match_length&&e.strstart-e.match_start>4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-3,s=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+3-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!=--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,s&&(b(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if((s=o._tr_tally(e,0,e.window[e.strstart-1]))&&b(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(s=o._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,4===t?(b(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(b(e,!1),0===e.strm.avail_out)?1:2}function A(e,t,i,s,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=s,this.func=r}function C(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=8,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new r.Buf16(1146),this.dyn_dtree=new r.Buf16(122),this.bl_tree=new r.Buf16(78),m(this.dyn_ltree),m(this.dyn_dtree),m(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new r.Buf16(16),this.heap=new r.Buf16(573),m(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new r.Buf16(573),m(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function S(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=2,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?42:p,e.adler=2===t.wrap?0:1,t.last_flush=0,o._tr_init(t),0):f(e,h)}function D(e){var t,i=S(e);return 0===i&&((t=e.state).window_size=2*t.w_size,m(t.head),t.max_lazy_match=s[t.level].max_lazy,t.good_match=s[t.level].good_length,t.nice_match=s[t.level].nice_length,t.max_chain_length=s[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=2,t.match_available=0,t.ins_h=0),i}function L(e,t,i,s,o,a){if(!e)return h;var n=1;if(-1===t&&(t=6),s<0?(n=0,s=-s):s>15&&(n=2,s-=16),o<1||o>9||8!==i||s<8||s>15||t<0||t>9||a<0||a>4)return f(e,h);8===s&&(s=9);var l=new C;return e.state=l,l.strm=e,l.wrap=n,l.gzhead=null,l.w_bits=s,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=o+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+3-1)/3),l.window=new r.Buf8(2*l.w_size),l.head=new r.Buf16(l.hash_size),l.prev=new r.Buf16(l.w_size),l.lit_bufsize=1<<o+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new r.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=a,l.method=i,D(e)}s=[new A(0,0,0,0,(function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(x(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var s=e.block_start+i;if((0===e.strstart||e.strstart>=s)&&(e.lookahead=e.strstart-s,e.strstart=s,b(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-u&&(b(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(b(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(b(e,!1),e.strm.avail_out),1)})),new A(4,4,8,4,w),new A(4,5,16,8,w),new A(4,6,32,32,w),new A(4,4,16,16,E),new A(8,16,32,32,E),new A(8,16,128,128,E),new A(8,32,128,256,E),new A(32,128,258,1024,E),new A(32,258,258,4096,E)],i.deflateInit=function(e,t){return L(e,t,8,15,8,0)},i.deflateInit2=L,i.deflateReset=D,i.deflateResetKeep=S,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?h:(e.state.gzhead=t,0):h},i.deflate=function(e,t){var i,r,a,l;if(!e||!e.state||t>5||t<0)return e?f(e,h):h;if(r=e.state,!e.output||!e.input&&0!==e.avail_in||r.status===_&&4!==t)return f(e,0===e.avail_out?-5:h);if(r.strm=e,i=r.last_flush,r.last_flush=t,42===r.status)if(2===r.wrap)e.adler=0,P(r,31),P(r,139),P(r,8),r.gzhead?(P(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),P(r,255&r.gzhead.time),P(r,r.gzhead.time>>8&255),P(r,r.gzhead.time>>16&255),P(r,r.gzhead.time>>24&255),P(r,9===r.level?2:r.strategy>=2||r.level<2?4:0),P(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(P(r,255&r.gzhead.extra.length),P(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=n(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69):(P(r,0),P(r,0),P(r,0),P(r,0),P(r,0),P(r,9===r.level?2:r.strategy>=2||r.level<2?4:0),P(r,3),r.status=p);else{var u=8+(r.w_bits-8<<4)<<8;u|=(r.strategy>=2||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(u|=32),u+=31-u%31,r.status=p,y(r,u),0!==r.strstart&&(y(r,e.adler>>>16),y(r,65535&e.adler)),e.adler=1}if(69===r.status)if(r.gzhead.extra){for(a=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),v(e),a=r.pending,r.pending!==r.pending_buf_size));)P(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=73)}else r.status=73;if(73===r.status)if(r.gzhead.name){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),v(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,P(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.gzindex=0,r.status=91)}else r.status=91;if(91===r.status)if(r.gzhead.comment){a=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),v(e),a=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,P(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>a&&(e.adler=n(e.adler,r.pending_buf,r.pending-a,a)),0===l&&(r.status=d)}else r.status=d;if(r.status===d&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&v(e),r.pending+2<=r.pending_buf_size&&(P(r,255&e.adler),P(r,e.adler>>8&255),e.adler=0,r.status=p)):r.status=p),0!==r.pending){if(v(e),0===e.avail_out)return r.last_flush=-1,0}else if(0===e.avail_in&&g(t)<=g(i)&&4!==t)return f(e,-5);if(r.status===_&&0!==e.avail_in)return f(e,-5);if(0!==e.avail_in||0!==r.lookahead||0!==t&&r.status!==_){var M=2===r.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(x(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(b(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(b(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(b(e,!1),0===e.strm.avail_out)?1:2}(r,t):3===r.strategy?function(e,t){for(var i,s,r,a,n=e.window;;){if(e.lookahead<=c){if(x(e),e.lookahead<=c&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(s=n[r=e.strstart-1])===n[++r]&&s===n[++r]&&s===n[++r]){a=e.strstart+c;do{}while(s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&s===n[++r]&&r<a);e.match_length=c-(a-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=o._tr_tally(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(b(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(b(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(b(e,!1),0===e.strm.avail_out)?1:2}(r,t):s[r.level].func(r,t);if(3!==M&&4!==M||(r.status=_),1===M||3===M)return 0===e.avail_out&&(r.last_flush=-1),0;if(2===M&&(1===t?o._tr_align(r):5!==t&&(o._tr_stored_block(r,0,0,!1),3===t&&(m(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),v(e),0===e.avail_out))return r.last_flush=-1,0}return 4!==t?0:r.wrap<=0?1:(2===r.wrap?(P(r,255&e.adler),P(r,e.adler>>8&255),P(r,e.adler>>16&255),P(r,e.adler>>24&255),P(r,255&e.total_in),P(r,e.total_in>>8&255),P(r,e.total_in>>16&255),P(r,e.total_in>>24&255)):(y(r,e.adler>>>16),y(r,65535&e.adler)),v(e),r.wrap>0&&(r.wrap=-r.wrap),0!==r.pending?0:1)},i.deflateEnd=function(e){var t;return e&&e.state?42!==(t=e.state.status)&&69!==t&&73!==t&&91!==t&&t!==d&&t!==p&&t!==_?f(e,h):(e.state=null,t===p?f(e,-3):0):h},i.deflateSetDictionary=function(e,t){var i,s,o,n,l,c,u,d,p=t.length;if(!e||!e.state)return h;if(2===(n=(i=e.state).wrap)||1===n&&42!==i.status||i.lookahead)return h;for(1===n&&(e.adler=a(e.adler,t,p,0)),i.wrap=0,p>=i.w_size&&(0===n&&(m(i.head),i.strstart=0,i.block_start=0,i.insert=0),d=new r.Buf8(i.w_size),r.arraySet(d,t,p-i.w_size,i.w_size,0),t=d,p=i.w_size),l=e.avail_in,c=e.next_in,u=e.input,e.avail_in=p,e.next_in=0,e.input=t,x(i);i.lookahead>=3;){s=i.strstart,o=i.lookahead-2;do{i.ins_h=(i.ins_h<<i.hash_shift^i.window[s+3-1])&i.hash_mask,i.prev[s&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=s,s++}while(--o);i.strstart=s,i.lookahead=2,x(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=2,i.match_available=0,e.next_in=c,e.input=u,e.avail_in=l,i.wrap=n,0},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":3,"./adler32":5,"./crc32":7,"./messages":13,"./trees":14}],9:[function(e,t,i){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],10:[function(e,t,i){t.exports=function(e,t){var i,s,r,o,a,n,l,h,c,u,d,p,_,f,g,m,v,b,P,y,M,x,w,E,A;i=e.state,s=e.next_in,E=e.input,r=s+(e.avail_in-5),o=e.next_out,A=e.output,a=o-(t-e.avail_out),n=o+(e.avail_out-257),l=i.dmax,h=i.wsize,c=i.whave,u=i.wnext,d=i.window,p=i.hold,_=i.bits,f=i.lencode,g=i.distcode,m=(1<<i.lenbits)-1,v=(1<<i.distbits)-1;e:do{_<15&&(p+=E[s++]<<_,_+=8,p+=E[s++]<<_,_+=8),b=f[p&m];t:for(;;){if(p>>>=P=b>>>24,_-=P,0==(P=b>>>16&255))A[o++]=65535&b;else{if(!(16&P)){if(0==(64&P)){b=f[(65535&b)+(p&(1<<P)-1)];continue t}if(32&P){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}y=65535&b,(P&=15)&&(_<P&&(p+=E[s++]<<_,_+=8),y+=p&(1<<P)-1,p>>>=P,_-=P),_<15&&(p+=E[s++]<<_,_+=8,p+=E[s++]<<_,_+=8),b=g[p&v];i:for(;;){if(p>>>=P=b>>>24,_-=P,!(16&(P=b>>>16&255))){if(0==(64&P)){b=g[(65535&b)+(p&(1<<P)-1)];continue i}e.msg="invalid distance code",i.mode=30;break e}if(M=65535&b,_<(P&=15)&&(p+=E[s++]<<_,(_+=8)<P&&(p+=E[s++]<<_,_+=8)),(M+=p&(1<<P)-1)>l){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=P,_-=P,M>(P=o-a)){if((P=M-P)>c&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(x=0,w=d,0===u){if(x+=h-P,P<y){y-=P;do{A[o++]=d[x++]}while(--P);x=o-M,w=A}}else if(u<P){if(x+=h+u-P,(P-=u)<y){y-=P;do{A[o++]=d[x++]}while(--P);if(x=0,u<y){y-=P=u;do{A[o++]=d[x++]}while(--P);x=o-M,w=A}}}else if(x+=u-P,P<y){y-=P;do{A[o++]=d[x++]}while(--P);x=o-M,w=A}for(;y>2;)A[o++]=w[x++],A[o++]=w[x++],A[o++]=w[x++],y-=3;y&&(A[o++]=w[x++],y>1&&(A[o++]=w[x++]))}else{x=o-M;do{A[o++]=A[x++],A[o++]=A[x++],A[o++]=A[x++],y-=3}while(y>2);y&&(A[o++]=A[x++],y>1&&(A[o++]=A[x++]))}break}}break}}while(s<r&&o<n);s-=y=_>>3,p&=(1<<(_-=y<<3))-1,e.next_in=s,e.next_out=o,e.avail_in=s<r?r-s+5:5-(s-r),e.avail_out=o<n?n-o+257:257-(o-n),i.hold=p,i.bits=_}},{}],11:[function(e,t,i){var s=e("../utils/common"),r=e("./adler32"),o=e("./crc32"),a=e("./inffast"),n=e("./inftrees"),l=-2,h=12,c=30;function u(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function d(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function p(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new s.Buf32(852),t.distcode=t.distdyn=new s.Buf32(592),t.sane=1,t.back=-1,0):l}function _(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,p(e)):l}function f(e,t){var i,s;return e&&e.state?(s=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?l:(null!==s.window&&s.wbits!==t&&(s.window=null),s.wrap=i,s.wbits=t,_(e))):l}function g(e,t){var i,s;return e?(s=new d,e.state=s,s.window=null,0!==(i=f(e,t))&&(e.state=null),i):l}var m,v,b=!0;function P(e){if(b){var t;for(m=new s.Buf32(512),v=new s.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(n(1,e.lens,0,288,m,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;n(2,e.lens,0,32,v,0,e.work,{bits:5}),b=!1}e.lencode=m,e.lenbits=9,e.distcode=v,e.distbits=5}function y(e,t,i,r){var o,a=e.state;return null===a.window&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new s.Buf8(a.wsize)),r>=a.wsize?(s.arraySet(a.window,t,i-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):((o=a.wsize-a.wnext)>r&&(o=r),s.arraySet(a.window,t,i-r,o,a.wnext),(r-=o)?(s.arraySet(a.window,t,i-r,r,0),a.wnext=r,a.whave=a.wsize):(a.wnext+=o,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=o))),0}i.inflateReset=_,i.inflateReset2=f,i.inflateResetKeep=p,i.inflateInit=function(e){return g(e,15)},i.inflateInit2=g,i.inflate=function(e,t){var i,d,p,_,f,g,m,v,b,M,x,w,E,A,C,S,D,L,B,T,R,F,N,I,O=0,k=new s.Buf8(4),V=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return l;(i=e.state).mode===h&&(i.mode=13),f=e.next_out,p=e.output,m=e.avail_out,_=e.next_in,d=e.input,g=e.avail_in,v=i.hold,b=i.bits,M=g,x=m,F=0;e:for(;;)switch(i.mode){case 1:if(0===i.wrap){i.mode=13;break}for(;b<16;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if(2&i.wrap&&35615===v){i.check=0,k[0]=255&v,k[1]=v>>>8&255,i.check=o(i.check,k,2,0),v=0,b=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&v)<<8)+(v>>8))%31){e.msg="incorrect header check",i.mode=c;break}if(8!=(15&v)){e.msg="unknown compression method",i.mode=c;break}if(b-=4,R=8+(15&(v>>>=4)),0===i.wbits)i.wbits=R;else if(R>i.wbits){e.msg="invalid window size",i.mode=c;break}i.dmax=1<<R,e.adler=i.check=1,i.mode=512&v?10:h,v=0,b=0;break;case 2:for(;b<16;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if(i.flags=v,8!=(255&i.flags)){e.msg="unknown compression method",i.mode=c;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=c;break}i.head&&(i.head.text=v>>8&1),512&i.flags&&(k[0]=255&v,k[1]=v>>>8&255,i.check=o(i.check,k,2,0)),v=0,b=0,i.mode=3;case 3:for(;b<32;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}i.head&&(i.head.time=v),512&i.flags&&(k[0]=255&v,k[1]=v>>>8&255,k[2]=v>>>16&255,k[3]=v>>>24&255,i.check=o(i.check,k,4,0)),v=0,b=0,i.mode=4;case 4:for(;b<16;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}i.head&&(i.head.xflags=255&v,i.head.os=v>>8),512&i.flags&&(k[0]=255&v,k[1]=v>>>8&255,i.check=o(i.check,k,2,0)),v=0,b=0,i.mode=5;case 5:if(1024&i.flags){for(;b<16;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}i.length=v,i.head&&(i.head.extra_len=v),512&i.flags&&(k[0]=255&v,k[1]=v>>>8&255,i.check=o(i.check,k,2,0)),v=0,b=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&((w=i.length)>g&&(w=g),w&&(i.head&&(R=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),s.arraySet(i.head.extra,d,_,w,R)),512&i.flags&&(i.check=o(i.check,d,w,_)),g-=w,_+=w,i.length-=w),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===g)break e;w=0;do{R=d[_+w++],i.head&&R&&i.length<65536&&(i.head.name+=String.fromCharCode(R))}while(R&&w<g);if(512&i.flags&&(i.check=o(i.check,d,w,_)),g-=w,_+=w,R)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===g)break e;w=0;do{R=d[_+w++],i.head&&R&&i.length<65536&&(i.head.comment+=String.fromCharCode(R))}while(R&&w<g);if(512&i.flags&&(i.check=o(i.check,d,w,_)),g-=w,_+=w,R)break e}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;b<16;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if(v!==(65535&i.check)){e.msg="header crc mismatch",i.mode=c;break}v=0,b=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=h;break;case 10:for(;b<32;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}e.adler=i.check=u(v),v=0,b=0,i.mode=11;case 11:if(0===i.havedict)return e.next_out=f,e.avail_out=m,e.next_in=_,e.avail_in=g,i.hold=v,i.bits=b,2;e.adler=i.check=1,i.mode=h;case h:if(5===t||6===t)break e;case 13:if(i.last){v>>>=7&b,b-=7&b,i.mode=27;break}for(;b<3;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}switch(i.last=1&v,b-=1,3&(v>>>=1)){case 0:i.mode=14;break;case 1:if(P(i),i.mode=20,6===t){v>>>=2,b-=2;break e}break;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=c}v>>>=2,b-=2;break;case 14:for(v>>>=7&b,b-=7&b;b<32;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if((65535&v)!=(v>>>16^65535)){e.msg="invalid stored block lengths",i.mode=c;break}if(i.length=65535&v,v=0,b=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(w=i.length){if(w>g&&(w=g),w>m&&(w=m),0===w)break e;s.arraySet(p,d,_,w,f),g-=w,_+=w,m-=w,f+=w,i.length-=w;break}i.mode=h;break;case 17:for(;b<14;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if(i.nlen=257+(31&v),v>>>=5,b-=5,i.ndist=1+(31&v),v>>>=5,b-=5,i.ncode=4+(15&v),v>>>=4,b-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=c;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;b<3;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}i.lens[V[i.have++]]=7&v,v>>>=3,b-=3}for(;i.have<19;)i.lens[V[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,N={bits:i.lenbits},F=n(0,i.lens,0,19,i.lencode,0,i.work,N),i.lenbits=N.bits,F){e.msg="invalid code lengths set",i.mode=c;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;S=(O=i.lencode[v&(1<<i.lenbits)-1])>>>16&255,D=65535&O,!((C=O>>>24)<=b);){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if(D<16)v>>>=C,b-=C,i.lens[i.have++]=D;else{if(16===D){for(I=C+2;b<I;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if(v>>>=C,b-=C,0===i.have){e.msg="invalid bit length repeat",i.mode=c;break}R=i.lens[i.have-1],w=3+(3&v),v>>>=2,b-=2}else if(17===D){for(I=C+3;b<I;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}b-=C,R=0,w=3+(7&(v>>>=C)),v>>>=3,b-=3}else{for(I=C+7;b<I;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}b-=C,R=0,w=11+(127&(v>>>=C)),v>>>=7,b-=7}if(i.have+w>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=c;break}for(;w--;)i.lens[i.have++]=R}}if(i.mode===c)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=c;break}if(i.lenbits=9,N={bits:i.lenbits},F=n(1,i.lens,0,i.nlen,i.lencode,0,i.work,N),i.lenbits=N.bits,F){e.msg="invalid literal/lengths set",i.mode=c;break}if(i.distbits=6,i.distcode=i.distdyn,N={bits:i.distbits},F=n(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,N),i.distbits=N.bits,F){e.msg="invalid distances set",i.mode=c;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(g>=6&&m>=258){e.next_out=f,e.avail_out=m,e.next_in=_,e.avail_in=g,i.hold=v,i.bits=b,a(e,x),f=e.next_out,p=e.output,m=e.avail_out,_=e.next_in,d=e.input,g=e.avail_in,v=i.hold,b=i.bits,i.mode===h&&(i.back=-1);break}for(i.back=0;S=(O=i.lencode[v&(1<<i.lenbits)-1])>>>16&255,D=65535&O,!((C=O>>>24)<=b);){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if(S&&0==(240&S)){for(L=C,B=S,T=D;S=(O=i.lencode[T+((v&(1<<L+B)-1)>>L)])>>>16&255,D=65535&O,!(L+(C=O>>>24)<=b);){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}v>>>=L,b-=L,i.back+=L}if(v>>>=C,b-=C,i.back+=C,i.length=D,0===S){i.mode=26;break}if(32&S){i.back=-1,i.mode=h;break}if(64&S){e.msg="invalid literal/length code",i.mode=c;break}i.extra=15&S,i.mode=22;case 22:if(i.extra){for(I=i.extra;b<I;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}i.length+=v&(1<<i.extra)-1,v>>>=i.extra,b-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;S=(O=i.distcode[v&(1<<i.distbits)-1])>>>16&255,D=65535&O,!((C=O>>>24)<=b);){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if(0==(240&S)){for(L=C,B=S,T=D;S=(O=i.distcode[T+((v&(1<<L+B)-1)>>L)])>>>16&255,D=65535&O,!(L+(C=O>>>24)<=b);){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}v>>>=L,b-=L,i.back+=L}if(v>>>=C,b-=C,i.back+=C,64&S){e.msg="invalid distance code",i.mode=c;break}i.offset=D,i.extra=15&S,i.mode=24;case 24:if(i.extra){for(I=i.extra;b<I;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}i.offset+=v&(1<<i.extra)-1,v>>>=i.extra,b-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=c;break}i.mode=25;case 25:if(0===m)break e;if(w=x-m,i.offset>w){if((w=i.offset-w)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=c;break}w>i.wnext?(w-=i.wnext,E=i.wsize-w):E=i.wnext-w,w>i.length&&(w=i.length),A=i.window}else A=p,E=f-i.offset,w=i.length;w>m&&(w=m),m-=w,i.length-=w;do{p[f++]=A[E++]}while(--w);0===i.length&&(i.mode=21);break;case 26:if(0===m)break e;p[f++]=i.length,m--,i.mode=21;break;case 27:if(i.wrap){for(;b<32;){if(0===g)break e;g--,v|=d[_++]<<b,b+=8}if(x-=m,e.total_out+=x,i.total+=x,x&&(e.adler=i.check=i.flags?o(i.check,p,x,f-x):r(i.check,p,x,f-x)),x=m,(i.flags?v:u(v))!==i.check){e.msg="incorrect data check",i.mode=c;break}v=0,b=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;b<32;){if(0===g)break e;g--,v+=d[_++]<<b,b+=8}if(v!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=c;break}v=0,b=0}i.mode=29;case 29:F=1;break e;case c:F=-3;break e;case 31:return-4;case 32:default:return l}return e.next_out=f,e.avail_out=m,e.next_in=_,e.avail_in=g,i.hold=v,i.bits=b,(i.wsize||x!==e.avail_out&&i.mode<c&&(i.mode<27||4!==t))&&y(e,e.output,e.next_out,x-e.avail_out),M-=e.avail_in,x-=e.avail_out,e.total_in+=M,e.total_out+=x,i.total+=x,i.wrap&&x&&(e.adler=i.check=i.flags?o(i.check,p,x,e.next_out-x):r(i.check,p,x,e.next_out-x)),e.data_type=i.bits+(i.last?64:0)+(i.mode===h?128:0)+(20===i.mode||15===i.mode?256:0),(0===M&&0===x||4===t)&&0===F&&(F=-5),F},i.inflateEnd=function(e){if(!e||!e.state)return l;var t=e.state;return t.window&&(t.window=null),e.state=null,0},i.inflateGetHeader=function(e,t){var i;return e&&e.state?0==(2&(i=e.state).wrap)?l:(i.head=t,t.done=!1,0):l},i.inflateSetDictionary=function(e,t){var i,s=t.length;return e&&e.state?0!==(i=e.state).wrap&&11!==i.mode?l:11===i.mode&&r(1,t,s,0)!==i.check?-3:y(e,t,s,s)?(i.mode=31,-4):(i.havedict=1,0):l},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":3,"./adler32":5,"./crc32":7,"./inffast":10,"./inftrees":12}],12:[function(e,t,i){var s=e("../utils/common"),r=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],a=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,i,l,h,c,u,d){var p,_,f,g,m,v,b,P,y,M=d.bits,x=0,w=0,E=0,A=0,C=0,S=0,D=0,L=0,B=0,T=0,R=null,F=0,N=new s.Buf16(16),I=new s.Buf16(16),O=null,k=0;for(x=0;x<=15;x++)N[x]=0;for(w=0;w<l;w++)N[t[i+w]]++;for(C=M,A=15;A>=1&&0===N[A];A--);if(C>A&&(C=A),0===A)return h[c++]=20971520,h[c++]=20971520,d.bits=1,0;for(E=1;E<A&&0===N[E];E++);for(C<E&&(C=E),L=1,x=1;x<=15;x++)if(L<<=1,(L-=N[x])<0)return-1;if(L>0&&(0===e||1!==A))return-1;for(I[1]=0,x=1;x<15;x++)I[x+1]=I[x]+N[x];for(w=0;w<l;w++)0!==t[i+w]&&(u[I[t[i+w]]++]=w);if(0===e?(R=O=u,v=19):1===e?(R=r,F-=257,O=o,k-=257,v=256):(R=a,O=n,v=-1),T=0,w=0,x=E,m=c,S=C,D=0,f=-1,g=(B=1<<C)-1,1===e&&B>852||2===e&&B>592)return 1;for(;;){b=x-D,u[w]<v?(P=0,y=u[w]):u[w]>v?(P=O[k+u[w]],y=R[F+u[w]]):(P=96,y=0),p=1<<x-D,E=_=1<<S;do{h[m+(T>>D)+(_-=p)]=b<<24|P<<16|y|0}while(0!==_);for(p=1<<x-1;T&p;)p>>=1;if(0!==p?(T&=p-1,T+=p):T=0,w++,0==--N[x]){if(x===A)break;x=t[i+u[w]]}if(x>C&&(T&g)!==f){for(0===D&&(D=C),m+=E,L=1<<(S=x-D);S+D<A&&!((L-=N[S+D])<=0);)S++,L<<=1;if(B+=1<<S,1===e&&B>852||2===e&&B>592)return 1;h[f=T&g]=C<<24|S<<16|m-c|0}}return 0!==T&&(h[m+T]=x-D<<24|64<<16|0),d.bits=C,0}},{"../utils/common":3}],13:[function(e,t,i){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],14:[function(e,t,i){var s=e("../utils/common");function r(e){for(var t=e.length;--t>=0;)e[t]=0}var o=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],a=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],l=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],h=new Array(576);r(h);var c=new Array(60);r(c);var u=new Array(512);r(u);var d=new Array(256);r(d);var p=new Array(29);r(p);var _,f,g,m=new Array(30);function v(e,t,i,s,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=s,this.max_length=r,this.has_stree=e&&e.length}function b(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function P(e){return e<256?u[e]:u[256+(e>>>7)]}function y(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function M(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<<e.bi_valid&65535,y(e,e.bi_buf),e.bi_buf=t>>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function x(e,t,i){M(e,i[2*t],i[2*t+1])}function w(e,t){var i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1}function E(e,t,i){var s,r,o=new Array(16),a=0;for(s=1;s<=15;s++)o[s]=a=a+i[s-1]<<1;for(r=0;r<=t;r++){var n=e[2*r+1];0!==n&&(e[2*r]=w(o[n]++,n))}}function A(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function C(e){e.bi_valid>8?y(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function S(e,t,i,s){var r=2*t,o=2*i;return e[r]<e[o]||e[r]===e[o]&&s[t]<=s[i]}function D(e,t,i){for(var s=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&S(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!S(t,s,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=s}function L(e,t,i){var s,r,n,l,h=0;if(0!==e.last_lit)do{s=e.pending_buf[e.d_buf+2*h]<<8|e.pending_buf[e.d_buf+2*h+1],r=e.pending_buf[e.l_buf+h],h++,0===s?x(e,r,t):(x(e,(n=d[r])+256+1,t),0!==(l=o[n])&&M(e,r-=p[n],l),x(e,n=P(--s),i),0!==(l=a[n])&&M(e,s-=m[n],l))}while(h<e.last_lit);x(e,256,t)}function B(e,t){var i,s,r,o=t.dyn_tree,a=t.stat_desc.static_tree,n=t.stat_desc.has_stree,l=t.stat_desc.elems,h=-1;for(e.heap_len=0,e.heap_max=573,i=0;i<l;i++)0!==o[2*i]?(e.heap[++e.heap_len]=h=i,e.depth[i]=0):o[2*i+1]=0;for(;e.heap_len<2;)o[2*(r=e.heap[++e.heap_len]=h<2?++h:0)]=1,e.depth[r]=0,e.opt_len--,n&&(e.static_len-=a[2*r+1]);for(t.max_code=h,i=e.heap_len>>1;i>=1;i--)D(e,o,i);r=l;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],D(e,o,1),s=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=s,o[2*r]=o[2*i]+o[2*s],e.depth[r]=(e.depth[i]>=e.depth[s]?e.depth[i]:e.depth[s])+1,o[2*i+1]=o[2*s+1]=r,e.heap[1]=r++,D(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,s,r,o,a,n,l=t.dyn_tree,h=t.max_code,c=t.stat_desc.static_tree,u=t.stat_desc.has_stree,d=t.stat_desc.extra_bits,p=t.stat_desc.extra_base,_=t.stat_desc.max_length,f=0;for(o=0;o<=15;o++)e.bl_count[o]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(o=l[2*l[2*(s=e.heap[i])+1]+1]+1)>_&&(o=_,f++),l[2*s+1]=o,s>h||(e.bl_count[o]++,a=0,s>=p&&(a=d[s-p]),n=l[2*s],e.opt_len+=n*(o+a),u&&(e.static_len+=n*(c[2*s+1]+a)));if(0!==f){do{for(o=_-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[_]--,f-=2}while(f>0);for(o=_;0!==o;o--)for(s=e.bl_count[o];0!==s;)(r=e.heap[--i])>h||(l[2*r+1]!==o&&(e.opt_len+=(o-l[2*r+1])*l[2*r],l[2*r+1]=o),s--)}}(e,t),E(o,h,e.bl_count)}function T(e,t,i){var s,r,o=-1,a=t[1],n=0,l=7,h=4;for(0===a&&(l=138,h=3),t[2*(i+1)+1]=65535,s=0;s<=i;s++)r=a,a=t[2*(s+1)+1],++n<l&&r===a||(n<h?e.bl_tree[2*r]+=n:0!==r?(r!==o&&e.bl_tree[2*r]++,e.bl_tree[32]++):n<=10?e.bl_tree[34]++:e.bl_tree[36]++,n=0,o=r,0===a?(l=138,h=3):r===a?(l=6,h=3):(l=7,h=4))}function R(e,t,i){var s,r,o=-1,a=t[1],n=0,l=7,h=4;for(0===a&&(l=138,h=3),s=0;s<=i;s++)if(r=a,a=t[2*(s+1)+1],!(++n<l&&r===a)){if(n<h)do{x(e,r,e.bl_tree)}while(0!=--n);else 0!==r?(r!==o&&(x(e,r,e.bl_tree),n--),x(e,16,e.bl_tree),M(e,n-3,2)):n<=10?(x(e,17,e.bl_tree),M(e,n-3,3)):(x(e,18,e.bl_tree),M(e,n-11,7));n=0,o=r,0===a?(l=138,h=3):r===a?(l=6,h=3):(l=7,h=4)}}r(m);var F=!1;function N(e,t,i,r){M(e,0+(r?1:0),3),function(e,t,i,r){C(e),y(e,i),y(e,~i),s.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}(e,t,i)}i._tr_init=function(e){F||(function(){var e,t,i,s,r,l=new Array(16);for(i=0,s=0;s<28;s++)for(p[s]=i,e=0;e<1<<o[s];e++)d[i++]=s;for(d[i-1]=s,r=0,s=0;s<16;s++)for(m[s]=r,e=0;e<1<<a[s];e++)u[r++]=s;for(r>>=7;s<30;s++)for(m[s]=r<<7,e=0;e<1<<a[s]-7;e++)u[256+r++]=s;for(t=0;t<=15;t++)l[t]=0;for(e=0;e<=143;)h[2*e+1]=8,e++,l[8]++;for(;e<=255;)h[2*e+1]=9,e++,l[9]++;for(;e<=279;)h[2*e+1]=7,e++,l[7]++;for(;e<=287;)h[2*e+1]=8,e++,l[8]++;for(E(h,287,l),e=0;e<30;e++)c[2*e+1]=5,c[2*e]=w(e,5);_=new v(h,o,257,286,15),f=new v(c,a,0,30,15),g=new v(new Array(0),n,0,19,7)}(),F=!0),e.l_desc=new b(e.dyn_ltree,_),e.d_desc=new b(e.dyn_dtree,f),e.bl_desc=new b(e.bl_tree,g),e.bi_buf=0,e.bi_valid=0,A(e)},i._tr_stored_block=N,i._tr_flush_block=function(e,t,i,s){var r,o,a=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),B(e,e.l_desc),B(e,e.d_desc),a=function(e){var t;for(T(e,e.dyn_ltree,e.l_desc.max_code),T(e,e.dyn_dtree,e.d_desc.max_code),B(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*l[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),r=e.opt_len+3+7>>>3,(o=e.static_len+3+7>>>3)<=r&&(r=o)):r=o=i+5,i+4<=r&&-1!==t?N(e,t,i,s):4===e.strategy||o===r?(M(e,2+(s?1:0),3),L(e,h,c)):(M(e,4+(s?1:0),3),function(e,t,i,s){var r;for(M(e,t-257,5),M(e,i-1,5),M(e,s-4,4),r=0;r<s;r++)M(e,e.bl_tree[2*l[r]+1],3);R(e,e.dyn_ltree,t-1),R(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,a+1),L(e,e.dyn_ltree,e.dyn_dtree)),A(e),s&&C(e)},i._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(d[i]+256+1)]++,e.dyn_dtree[2*P(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){M(e,2,3),x(e,256,h),function(e){16===e.bi_valid?(y(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},{"../utils/common":3}],15:[function(e,t,i){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],"/":[function(e,t,i){var s={};(0,e("./lib/utils/common").assign)(s,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=s},{"./lib/deflate":1,"./lib/inflate":2,"./lib/utils/common":3,"./lib/zlib/constants":6}]},{},[])("/")}));var sa=Object.freeze({__proto__:null});let ra=window.pako||sa;ra.inflate||(ra=ra.default);const oa=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}(),aa={version:1,parse:function(e,t,i,s){!function(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.meshPositions,h=i.meshIndices,c=i.meshEdgesIndices,d=i.meshColors,p=JSON.parse(i.entityIDs),_=i.entityMeshes,g=i.entityIsObjects,m=l.length,v=_.length;for(let b=0;b<v;b++){const P=p[b],y=t.globalizeObjectIds?u.globalizeObjectId(s.id,P):P,M=e.metaScene.metaObjects[y],x={},w={};if(M){if(t.excludeTypesMap&&M.type&&t.excludeTypesMap[M.type])continue;if(t.includeTypesMap&&M.type&&!t.includeTypesMap[M.type])continue;const e=t.objectDefaults?t.objectDefaults[M.type]||t.objectDefaults.DEFAULT:null;e&&(!1===e.visible&&(x.visible=!1),!1===e.pickable&&(x.pickable=!1),e.colorize&&(w.color=e.colorize),void 0!==e.opacity&&null!==e.opacity&&(w.opacity=e.opacity))}else if(t.excludeUnclassifiedObjects)continue;const E=b===v-1,A=[];for(let e=_[b],t=E?_.length:_[b+1];e<t;e++){const t=e===m-1,u=y+".mesh."+e,p=oa(d.subarray(4*e,4*e+3)),_=d[4*e+3]/255;s.createMesh(f.apply(w,{id:u,primitive:"triangles",positions:r.subarray(l[e],t?r.length:l[e+1]),normals:o.subarray(l[e],t?r.length:l[e+1]),indices:a.subarray(h[e],t?a.length:h[e+1]),edgeIndices:n.subarray(c[e],t?n.length:c[e+1]),positionsDecodeMatrix:i.positionsDecodeMatrix,color:p,opacity:_})),A.push(u)}s.createEntity(f.apply(x,{id:y,isObject:1===g[b],meshIds:A}))}}(e,t,function(e){return{positions:new Uint16Array(ra.inflate(e.positions).buffer),normals:new Int8Array(ra.inflate(e.normals).buffer),indices:new Uint32Array(ra.inflate(e.indices).buffer),edgeIndices:new Uint32Array(ra.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(ra.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(ra.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(ra.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(ra.inflate(e.meshColors).buffer),entityIDs:ra.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(ra.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(ra.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(ra.inflate(e.positionsDecodeMatrix).buffer)}}(function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],positionsDecodeMatrix:e[11]}}(i)),s)}};let na=window.pako||sa;na.inflate||(na=na.default);const la=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}(),ha={version:2,parse:function(e,t,i,s){!function(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.meshPositions,h=i.meshIndices,c=i.meshEdgesIndices,d=i.meshColors,p=JSON.parse(i.entityIDs),_=i.entityMeshes,g=i.entityIsObjects,m=i.entityMeshIds,v=i.entityMatrices,b=i.entityUsesInstancing,P=l.length,y=_.length,M={};for(let x=0;x<y;x++){const w=p[x],E=t.globalizeObjectIds?u.globalizeObjectId(s.id,w):w,A=e.metaScene.metaObjects[E],C={},S={},D=v.subarray(16*x,16*x+16);if(A){if(t.excludeTypesMap&&A.type&&t.excludeTypesMap[A.type])continue;if(t.includeTypesMap&&A.type&&!t.includeTypesMap[A.type])continue;const e=t.objectDefaults?t.objectDefaults[A.type]||t.objectDefaults.DEFAULT:null;e&&(!1===e.visible&&(C.visible=!1),!1===e.pickable&&(C.pickable=!1),e.colorize&&(S.color=e.colorize),void 0!==e.opacity&&null!==e.opacity&&(S.opacity=e.opacity))}else if(t.excludeUnclassifiedObjects)continue;const L=x===y-1,B=[];for(let e=_[x],t=L?m.length:_[x+1];e<t;e++){const t=m[e],u=t===P-1,p=E+".mesh."+t,_=la(d.subarray(4*t,4*t+3)),g=d[4*t+3]/255,v=r.subarray(l[t],u?r.length:l[t+1]),y=o.subarray(l[t],u?r.length:l[t+1]),w=a.subarray(h[t],u?a.length:h[t+1]),A=n.subarray(c[t],u?n.length:c[t+1]);if(1===b[x]){const e="geometry."+t;e in M||(s.createGeometry({id:e,positions:v,normals:y,indices:w,edgeIndices:A,primitive:"triangles",positionsDecodeMatrix:i.positionsDecodeMatrix}),M[e]=!0),s.createMesh(f.apply(S,{id:p,color:_,opacity:g,matrix:D,geometryId:e})),B.push(p)}else s.createMesh(f.apply(S,{id:p,primitive:"triangles",positions:v,normals:y,indices:w,edgeIndices:A,positionsDecodeMatrix:i.positionsDecodeMatrix,color:_,opacity:g})),B.push(p)}B.length&&s.createEntity(f.apply(C,{id:E,isObject:1===g[x],meshIds:B}))}}(e,t,function(e){return{positions:new Uint16Array(na.inflate(e.positions).buffer),normals:new Int8Array(na.inflate(e.normals).buffer),indices:new Uint32Array(na.inflate(e.indices).buffer),edgeIndices:new Uint32Array(na.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(na.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(na.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(na.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(na.inflate(e.meshColors).buffer),entityIDs:na.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(na.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(na.inflate(e.entityIsObjects).buffer),positionsDecodeMatrix:new Float32Array(na.inflate(e.positionsDecodeMatrix).buffer),entityMeshIds:new Uint32Array(na.inflate(e.entityMeshIds).buffer),entityMatrices:new Float32Array(na.inflate(e.entityMatrices).buffer),entityUsesInstancing:new Uint8Array(na.inflate(e.entityUsesInstancing).buffer)}}(function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],positionsDecodeMatrix:e[11],entityMeshIds:e[12],entityMatrices:e[13],entityUsesInstancing:e[14]}}(i)),s)}};let ca=window.pako||sa;ca.inflate||(ca=ca.default);const ua=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}(),da={version:3,parse:function(e,t,i,s){!function(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.meshPositions,h=i.meshIndices,c=i.meshEdgesIndices,d=i.meshColors,p=JSON.parse(i.entityIDs),_=i.entityMeshes,g=i.entityIsObjects,m=i.entityMeshIds,v=i.entityMatrices,b=i.entityUsesInstancing,P=l.length,y=_.length,M={};for(let D=0;D<y;D++){const L=p[D],B=t.globalizeObjectIds?u.globalizeObjectId(s.id,L):L,T=e.metaScene.metaObjects[B],R={},F={},N=v.subarray(16*D,16*D+16);if(T){if(t.excludeTypesMap&&T.type&&t.excludeTypesMap[T.type])continue;if(t.includeTypesMap&&T.type&&!t.includeTypesMap[T.type])continue;const e=t.objectDefaults?t.objectDefaults[T.type]||t.objectDefaults.DEFAULT:null;e&&(!1===e.visible&&(R.visible=!1),!1===e.pickable&&(R.pickable=!1),e.colorize&&(F.color=e.colorize),void 0!==e.opacity&&null!==e.opacity&&(F.opacity=e.opacity))}else if(t.excludeUnclassifiedObjects)continue;const I=D===y-1,O=[];for(let e=_[D],t=I?m.length:_[D+1];e<t;e++){var x=m[e];const t=x===P-1,u=B+".mesh."+x,p=ua(d.subarray(4*x,4*x+3)),_=d[4*x+3]/255;var w=r.subarray(l[x],t?r.length:l[x+1]),E=o.subarray(l[x],t?r.length:l[x+1]),A=a.subarray(h[x],t?a.length:h[x+1]),C=n.subarray(c[x],t?n.length:c[x+1]);if(1===b[D]){var S="geometry."+x;S in M||(s.createGeometry({id:S,positions:w,normals:E,indices:A,edgeIndices:C,primitive:"triangles",positionsDecodeMatrix:i.instancedPositionsDecodeMatrix}),M[S]=!0),s.createMesh(f.apply(F,{id:u,color:p,opacity:_,matrix:N,geometryId:S})),O.push(u)}else s.createMesh(f.apply(F,{id:u,primitive:"triangles",positions:w,normals:E,indices:A,edgeIndices:C,positionsDecodeMatrix:i.batchedPositionsDecodeMatrix,color:p,opacity:_})),O.push(u)}O.length&&s.createEntity(f.apply(R,{id:B,isObject:1===g[D],meshIds:O}))}}(e,t,function(e){return{positions:new Uint16Array(ca.inflate(e.positions).buffer),normals:new Int8Array(ca.inflate(e.normals).buffer),indices:new Uint32Array(ca.inflate(e.indices).buffer),edgeIndices:new Uint32Array(ca.inflate(e.edgeIndices).buffer),meshPositions:new Uint32Array(ca.inflate(e.meshPositions).buffer),meshIndices:new Uint32Array(ca.inflate(e.meshIndices).buffer),meshEdgesIndices:new Uint32Array(ca.inflate(e.meshEdgesIndices).buffer),meshColors:new Uint8Array(ca.inflate(e.meshColors).buffer),entityIDs:ca.inflate(e.entityIDs,{to:"string"}),entityMeshes:new Uint32Array(ca.inflate(e.entityMeshes).buffer),entityIsObjects:new Uint8Array(ca.inflate(e.entityIsObjects).buffer),instancedPositionsDecodeMatrix:new Float32Array(ca.inflate(e.instancedPositionsDecodeMatrix).buffer),batchedPositionsDecodeMatrix:new Float32Array(ca.inflate(e.batchedPositionsDecodeMatrix).buffer),entityMeshIds:new Uint32Array(ca.inflate(e.entityMeshIds).buffer),entityMatrices:new Float32Array(ca.inflate(e.entityMatrices).buffer),entityUsesInstancing:new Uint8Array(ca.inflate(e.entityUsesInstancing).buffer)}}(function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],meshPositions:e[4],meshIndices:e[5],meshEdgesIndices:e[6],meshColors:e[7],entityIDs:e[8],entityMeshes:e[9],entityIsObjects:e[10],instancedPositionsDecodeMatrix:e[11],batchedPositionsDecodeMatrix:e[12],entityMeshIds:e[13],entityMatrices:e[14],entityUsesInstancing:e[15]}}(i)),s)}};let pa=window.pako||sa;pa.inflate||(pa=pa.default);const _a=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}(),fa={version:4,parse:function(e,t,i,s){!function(e,t,i,s){s.positionsCompression="precompressed",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.decodeMatrices,h=i.matrices,c=i.eachPrimitivePositionsAndNormalsPortion,u=i.eachPrimitiveIndicesPortion,d=i.eachPrimitiveEdgeIndicesPortion,p=i.eachPrimitiveDecodeMatricesPortion,_=i.eachPrimitiveColor,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),v=i.eachEntityPrimitiveInstancesPortion,b=i.eachEntityMatricesPortion,P=c.length,y=g.length,M=new Uint8Array(P),x=new Uint32Array(P),w=m.length;for(let e=0;e<P;e++)x[e]=e;x.sort(((e,t)=>p[e]<p[t]?-1:p[e]>p[t]?1:0));for(let e=0;e<y;e++)M[g[e]]++;const E={};for(let e=0;e<w;e++){const t=w-1,i=e===t,s=v[e],r=i?v[t]:v[e+1];for(let t=s;t<r;t++){const i=g[t];M[i]>1||(E[i]=e)}}for(let e=0;e<P;e++){const t=x[e],i=t===P-1,h=M[t]>1,g=_a(_.subarray(4*t,4*t+3)),v=_[4*t+3]/255,b=r.subarray(c[t],i?r.length:c[t+1]),y=o.subarray(c[t],i?o.length:c[t+1]),w=a.subarray(u[t],i?a.length:u[t+1]),C=n.subarray(d[t],i?n.length:d[t+1]),S=l.subarray(p[t],p[t]+16);if(h){var A="geometry"+t;s.createGeometry({id:A,primitive:"triangles",positions:b,normals:y,indices:w,edgeIndices:C,positionsDecodeMatrix:S})}else{const e=t;m[E[t]];const i={};s.createMesh(f.apply(i,{id:e,primitive:"triangles",positions:b,normals:y,indices:w,edgeIndices:C,positionsDecodeMatrix:S,color:g,opacity:v}))}}let C=0;for(let e=0;e<w;e++){const t=w-1,i=e===t,r=m[e],o=v[e],a=i?v[t]:v[e+1],n=[];for(let t=o;t<a;t++){const i=g[t];if(M[i]>1){const t={},r="instance."+C++,o="geometry"+i,a=16*b[e],l=h.subarray(a,a+16);s.createMesh(f.apply(t,{id:r,geometryId:o,matrix:l})),n.push(r)}else n.push(i)}if(n.length>0){const e={};s.createEntity(f.apply(e,{id:r,isObject:!0,meshIds:n}))}}}(0,0,function(e){return{positions:new Uint16Array(pa.inflate(e.positions).buffer),normals:new Int8Array(pa.inflate(e.normals).buffer),indices:new Uint32Array(pa.inflate(e.indices).buffer),edgeIndices:new Uint32Array(pa.inflate(e.edgeIndices).buffer),decodeMatrices:new Float32Array(pa.inflate(e.decodeMatrices).buffer),matrices:new Float32Array(pa.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(pa.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(pa.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(pa.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveDecodeMatricesPortion:new Uint32Array(pa.inflate(e.eachPrimitiveDecodeMatricesPortion).buffer),eachPrimitiveColor:new Uint8Array(pa.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(pa.inflate(e.primitiveInstances).buffer),eachEntityId:pa.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(pa.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(pa.inflate(e.eachEntityMatricesPortion).buffer)}}(function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],decodeMatrices:e[4],matrices:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveDecodeMatricesPortion:e[9],eachPrimitiveColor:e[10],primitiveInstances:e[11],eachEntityId:e[12],eachEntityPrimitiveInstancesPortion:e[13],eachEntityMatricesPortion:e[14],eachEntityMatrix:e[15]}}(i)),s)}};let ga=window.pako||sa;ga.inflate||(ga=ga.default);const ma=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}(),va={version:5,parse:function(e,t,i,s){!function(e,t,i,s){s.positionsCompression="disabled",s.normalsCompression="precompressed";const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.matrices,h=i.eachPrimitivePositionsAndNormalsPortion,c=i.eachPrimitiveIndicesPortion,u=i.eachPrimitiveEdgeIndicesPortion,d=i.eachPrimitiveColor,p=i.primitiveInstances,_=JSON.parse(i.eachEntityId),g=i.eachEntityPrimitiveInstancesPortion,m=i.eachEntityMatricesPortion,v=h.length,b=p.length,P=new Uint8Array(v),y=_.length;for(let e=0;e<b;e++)P[p[e]]++;const M={};for(let e=0;e<y;e++){const t=y-1,i=e===t,s=g[e],r=i?g[t]:g[e+1];for(let t=s;t<r;t++){const i=p[t];P[i]>1||(M[i]=e)}}for(let e=0;e<v;e++){const t=e===v-1,i=P[e]>1,l=ma(d.subarray(4*e,4*e+3)),p=d[4*e+3]/255,g=r.subarray(h[e],t?r.length:h[e+1]),m=o.subarray(h[e],t?o.length:h[e+1]),b=a.subarray(c[e],t?a.length:c[e+1]),y=n.subarray(u[e],t?n.length:u[e+1]);if(i){var x="geometry"+e;s.createGeometry({id:x,primitive:"triangles",positions:g,normals:m,indices:b,edgeIndices:y})}else{const t=e;_[M[e]];const i={};s.createMesh(f.apply(i,{id:t,primitive:"triangles",positions:g,normals:m,indices:b,edgeIndices:y,color:l,opacity:p}))}}let w=0;for(let e=0;e<y;e++){const t=y-1,i=e===t,r=_[e],o=g[e],a=i?g[t]:g[e+1],n=[];for(let t=o;t<a;t++){const i=p[t];if(P[i]>1){const t={},r="instance."+w++,o="geometry"+i,a=16*m[e],h=l.subarray(a,a+16);s.createMesh(f.apply(t,{id:r,geometryId:o,matrix:h})),n.push(r)}else n.push(i)}if(n.length>0){const e={};s.createEntity(f.apply(e,{id:r,isObject:!0,meshIds:n}))}}}(0,0,function(e){return{positions:new Float32Array(ga.inflate(e.positions).buffer),normals:new Int8Array(ga.inflate(e.normals).buffer),indices:new Uint32Array(ga.inflate(e.indices).buffer),edgeIndices:new Uint32Array(ga.inflate(e.edgeIndices).buffer),matrices:new Float32Array(ga.inflate(e.matrices).buffer),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(ga.inflate(e.eachPrimitivePositionsAndNormalsPortion).buffer),eachPrimitiveIndicesPortion:new Uint32Array(ga.inflate(e.eachPrimitiveIndicesPortion).buffer),eachPrimitiveEdgeIndicesPortion:new Uint32Array(ga.inflate(e.eachPrimitiveEdgeIndicesPortion).buffer),eachPrimitiveColor:new Uint8Array(ga.inflate(e.eachPrimitiveColor).buffer),primitiveInstances:new Uint32Array(ga.inflate(e.primitiveInstances).buffer),eachEntityId:ga.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(ga.inflate(e.eachEntityPrimitiveInstancesPortion).buffer),eachEntityMatricesPortion:new Uint32Array(ga.inflate(e.eachEntityMatricesPortion).buffer)}}(function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],eachPrimitivePositionsAndNormalsPortion:e[5],eachPrimitiveIndicesPortion:e[6],eachPrimitiveEdgeIndicesPortion:e[7],eachPrimitiveColor:e[8],primitiveInstances:e[9],eachEntityId:e[10],eachEntityPrimitiveInstancesPortion:e[11],eachEntityMatricesPortion:e[12]}}(i)),s)}};let ba=window.pako||sa;ba.inflate||(ba=ba.default);const Pa=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}(),ya={version:6,parse:function(e,t,i,s){!function(e,t,i,s){const r=i.positions,o=i.normals,a=i.indices,n=i.edgeIndices,l=i.matrices,h=i.reusedPrimitivesDecodeMatrix,c=i.eachPrimitivePositionsAndNormalsPortion,d=i.eachPrimitiveIndicesPortion,p=i.eachPrimitiveEdgeIndicesPortion,_=i.eachPrimitiveColorAndOpacity,g=i.primitiveInstances,m=JSON.parse(i.eachEntityId),v=i.eachEntityPrimitiveInstancesPortion,b=i.eachEntityMatricesPortion,P=i.eachTileAABB,y=i.eachTileEntitiesPortion,M=c.length,x=g.length,w=m.length,E=y.length;let A=0;const C=new Uint32Array(M);for(let e=0;e<x;e++){const t=g[e];void 0!==C[t]?C[t]++:C[t]=1}const S=u.vec3(),D=u.AABB3();for(let i=0;i<E;i++){const x=i===E-1,L=y[i],B=x?w:y[i+1],T=6*i,R=P.subarray(T,T+6);u.getAABB3Center(R,S),D[0]=R[0]-S[0],D[1]=R[1]-S[1],D[2]=R[2]-S[2],D[3]=R[3]-S[0],D[4]=R[4]-S[1],D[5]=R[5]-S[2];const F=Xe.createPositionsDecodeMatrix(D),N={};for(let P=L;P<B;P++){const y=m[P],x=t.globalizeObjectIds?u.globalizeObjectId(s.id,y):y,E=b[P],D=l.slice(E,E+16),L=P===w-1,B=v[P],T=L?g.length:v[P+1],R=[],I=e.metaScene.metaObjects[x],O={},k={};if(I){if(t.excludeTypesMap&&I.type&&t.excludeTypesMap[I.type])continue;if(t.includeTypesMap&&I.type&&!t.includeTypesMap[I.type])continue;const e=t.objectDefaults?t.objectDefaults[I.type]||t.objectDefaults.DEFAULT:null;e&&(!1===e.visible&&(O.visible=!1),!1===e.pickable&&(O.pickable=!1),e.colorize&&(k.color=e.colorize),void 0!==e.opacity&&null!==e.opacity&&(k.opacity=e.opacity))}else if(t.excludeUnclassifiedObjects)continue;for(let e=B;e<T;e++){const t=g[e],l=C[t]>1,u=t===M-1,m=r.subarray(c[t],u?r.length:c[t+1]),v=o.subarray(c[t],u?o.length:c[t+1]),b=a.subarray(d[t],u?a.length:d[t+1]),P=n.subarray(p[t],u?n.length:p[t+1]),y=Pa(_.subarray(4*t,4*t+3)),x=_[4*t+3]/255,w=A++;if(l){const e="geometry."+i+"."+t;N[e]||(s.createGeometry({id:e,rtcCenter:S,primitive:"triangles",positions:m,normals:v,indices:b,edgeIndices:P,positionsDecodeMatrix:h}),N[e]=!0),s.createMesh(f.apply(k,{id:w,geometryId:e,matrix:D,color:y,opacity:x})),R.push(w)}else s.createMesh(f.apply(k,{id:w,rtcCenter:S,primitive:"triangles",positions:m,normals:v,indices:b,edgeIndices:P,positionsDecodeMatrix:F,color:y,opacity:x})),R.push(w)}R.length>0&&s.createEntity(f.apply(O,{id:x,isObject:!0,meshIds:R}))}}}(e,t,function(e){function t(e,t){return 0===e.length?[]:ba.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedPrimitivesDecodeMatrix:new Float32Array(t(e.reusedPrimitivesDecodeMatrix)),eachPrimitivePositionsAndNormalsPortion:new Uint32Array(t(e.eachPrimitivePositionsAndNormalsPortion)),eachPrimitiveIndicesPortion:new Uint32Array(t(e.eachPrimitiveIndicesPortion)),eachPrimitiveEdgeIndicesPortion:new Uint32Array(t(e.eachPrimitiveEdgeIndicesPortion)),eachPrimitiveColorAndOpacity:new Uint8Array(t(e.eachPrimitiveColorAndOpacity)),primitiveInstances:new Uint32Array(t(e.primitiveInstances)),eachEntityId:ba.inflate(e.eachEntityId,{to:"string"}),eachEntityPrimitiveInstancesPortion:new Uint32Array(t(e.eachEntityPrimitiveInstancesPortion)),eachEntityMatricesPortion:new Uint32Array(t(e.eachEntityMatricesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(function(e){return{positions:e[0],normals:e[1],indices:e[2],edgeIndices:e[3],matrices:e[4],reusedPrimitivesDecodeMatrix:e[5],eachPrimitivePositionsAndNormalsPortion:e[6],eachPrimitiveIndicesPortion:e[7],eachPrimitiveEdgeIndicesPortion:e[8],eachPrimitiveColorAndOpacity:e[9],primitiveInstances:e[10],eachEntityId:e[11],eachEntityPrimitiveInstancesPortion:e[12],eachEntityMatricesPortion:e[13],eachTileAABB:e[14],eachTileEntitiesPortion:e[15]}}(i)),s)}};let Ma=window.pako||sa;Ma.inflate||(Ma=Ma.default);const xa=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}(),wa={version:7,parse:function(e,t,i,s){!function(e,t,i,s){const r=i.positions,o=i.normals,a=i.colors,n=i.indices,l=i.edgeIndices,h=i.matrices,c=i.reusedGeometriesDecodeMatrix,d=i.eachGeometryPrimitiveType,p=i.eachGeometryPositionsPortion,_=i.eachGeometryNormalsPortion,g=i.eachGeometryColorsPortion,m=i.eachGeometryIndicesPortion,v=i.eachGeometryEdgeIndicesPortion,b=i.eachMeshGeometriesPortion,P=i.eachMeshMatricesPortion,y=i.eachMeshMaterial,M=JSON.parse(i.eachEntityId),x=i.eachEntityMeshesPortion,w=i.eachTileAABB,E=i.eachTileEntitiesPortion,A=p.length,C=b.length,S=M.length,D=E.length;let L=0;const B=new Uint32Array(A);for(let e=0;e<C;e++){const t=b[e];void 0!==B[t]?B[t]++:B[t]=1}const T=u.vec3(),R=u.AABB3();for(let i=0;i<D;i++){const C=i===D-1,F=E[i],N=C?S:E[i+1],I=6*i,O=w.subarray(I,I+6);u.getAABB3Center(O,T),R[0]=O[0]-T[0],R[1]=O[1]-T[1],R[2]=O[2]-T[2],R[3]=O[3]-T[0],R[4]=O[4]-T[1],R[5]=O[5]-T[2];const k=Xe.createPositionsDecodeMatrix(R),V={};for(let w=F;w<N;w++){const E=M[w],C=t.globalizeObjectIds?u.globalizeObjectId(s.id,E):E,D=w===S-1,R=x[w],F=D?b.length:x[w+1],N=[],I=e.metaScene.metaObjects[C],O={},j={};if(I){if(t.excludeTypesMap&&I.type&&t.excludeTypesMap[I.type])continue;if(t.includeTypesMap&&I.type&&!t.includeTypesMap[I.type])continue;const e=t.objectDefaults?t.objectDefaults[I.type]||t.objectDefaults.DEFAULT:null;e&&(!1===e.visible&&(O.visible=!1),!1===e.pickable&&(O.pickable=!1),e.colorize&&(j.color=e.colorize),void 0!==e.opacity&&null!==e.opacity&&(j.opacity=e.opacity),void 0!==e.metallic&&null!==e.metallic&&(j.metallic=e.metallic),void 0!==e.roughness&&null!==e.roughness&&(j.roughness=e.roughness))}else if(t.excludeUnclassifiedObjects)continue;for(let e=R;e<F;e++){const t=b[e],u=B[t]>1,M=t===A-1,x=xa(y.subarray(6*e,6*e+3)),w=y[6*e+3]/255,E=y[6*e+4]/255,C=y[6*e+5]/255,S=L++;if(u){const u=P[e],b=h.slice(u,u+16),y="geometry."+i+"."+t;if(!V[y]){let e,i,h,u,f,b;switch(d[t]){case 0:e="solid",i=r.subarray(p[t],M?r.length:p[t+1]),h=o.subarray(_[t],M?o.length:_[t+1]),f=n.subarray(m[t],M?n.length:m[t+1]),b=l.subarray(v[t],M?l.length:v[t+1]);break;case 1:e="surface",i=r.subarray(p[t],M?r.length:p[t+1]),h=o.subarray(_[t],M?o.length:_[t+1]),f=n.subarray(m[t],M?n.length:m[t+1]),b=l.subarray(v[t],M?l.length:v[t+1]);break;case 2:e="points",i=r.subarray(p[t],M?r.length:p[t+1]),u=a.subarray(g[t],M?a.length:g[t+1]);break;case 3:e="lines",i=r.subarray(p[t],M?r.length:p[t+1]),f=n.subarray(m[t],M?n.length:m[t+1]);break;default:continue}s.createGeometry({id:y,rtcCenter:T,primitive:e,positions:i,normals:h,colors:u,indices:f,edgeIndices:b,positionsDecodeMatrix:c}),V[y]=!0}s.createMesh(f.apply(j,{id:S,geometryId:y,matrix:b,color:x,metallic:E,roughness:C,opacity:w})),N.push(S)}else{let e,i,h,c,u,b;switch(d[t]){case 0:e="solid",i=r.subarray(p[t],M?r.length:p[t+1]),h=o.subarray(_[t],M?o.length:_[t+1]),u=n.subarray(m[t],M?n.length:m[t+1]),b=l.subarray(v[t],M?l.length:v[t+1]);break;case 1:e="surface",i=r.subarray(p[t],M?r.length:p[t+1]),h=o.subarray(_[t],M?o.length:_[t+1]),u=n.subarray(m[t],M?n.length:m[t+1]),b=l.subarray(v[t],M?l.length:v[t+1]);break;case 2:e="points",i=r.subarray(p[t],M?r.length:p[t+1]),c=a.subarray(g[t],M?a.length:g[t+1]);break;case 3:e="lines",i=r.subarray(p[t],M?r.length:p[t+1]),u=n.subarray(m[t],M?n.length:m[t+1]);break;default:continue}s.createMesh(f.apply(j,{id:S,rtcCenter:T,primitive:e,positions:i,normals:h,colors:c,indices:u,edgeIndices:b,positionsDecodeMatrix:k,color:x,metallic:E,roughness:C,opacity:w})),N.push(S)}}N.length>0&&s.createEntity(f.apply(O,{id:C,isObject:!0,meshIds:N}))}}}(e,t,function(e){function t(e,t){return 0===e.length?[]:Ma.inflate(e,t).buffer}return{positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityId:Ma.inflate(e.eachEntityId,{to:"string"}),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(function(e){return{positions:e[0],normals:e[1],colors:e[2],indices:e[3],edgeIndices:e[4],matrices:e[5],reusedGeometriesDecodeMatrix:e[6],eachGeometryPrimitiveType:e[7],eachGeometryPositionsPortion:e[8],eachGeometryNormalsPortion:e[9],eachGeometryColorsPortion:e[10],eachGeometryIndicesPortion:e[11],eachGeometryEdgeIndicesPortion:e[12],eachMeshGeometriesPortion:e[13],eachMeshMatricesPortion:e[14],eachMeshMaterial:e[15],eachEntityId:e[16],eachEntityMeshesPortion:e[17],eachTileAABB:e[18],eachTileEntitiesPortion:e[19]}}(i)),s)}};let Ea=window.pako||sa;Ea.inflate||(Ea=Ea.default);const Aa=function(){const e=new Float32Array(3);return function(t){return e[0]=t[0]/255,e[1]=t[1]/255,e[2]=t[2]/255,e}}(),Ca={version:8,parse:function(e,t,i,s){!function(e,t,i,s){const r=JSON.parse(i.types),o=JSON.parse(i.eachMetaObjectId),a=i.eachMetaObjectType,n=JSON.parse(i.eachMetaObjectName),l=i.eachMetaObjectParent,h=i.positions,c=i.normals,d=i.colors,p=i.indices,_=i.edgeIndices,g=i.matrices,m=i.reusedGeometriesDecodeMatrix,v=i.eachGeometryPrimitiveType,b=i.eachGeometryPositionsPortion,P=i.eachGeometryNormalsPortion,y=i.eachGeometryColorsPortion,M=i.eachGeometryIndicesPortion,x=i.eachGeometryEdgeIndicesPortion,w=i.eachMeshGeometriesPortion,E=i.eachMeshMatricesPortion,A=i.eachMeshMaterial,C=i.eachEntityMetaObject,S=i.eachEntityMeshesPortion,D=i.eachTileAABB,L=i.eachTileEntitiesPortion,B=o.length,T=b.length,R=w.length,F=C.length,N=L.length;let I=0;const O=s.id;if(!e.metaScene.metaModels[O]){const i={metaObjects:[]};for(let e=0;e<B;e++){const t=o[e],s=r[a[e]]||"default",h=n[e],c=l[e],u=c!==e?o[c]:null;i.metaObjects.push({id:t,type:s,name:h,parent:u})}e.metaScene.createMetaModel(O,i,{includeTypes:t.includeTypes,excludeTypes:t.excludeTypes,globalizeObjectIds:t.globalizeObjectIds}),s.once("destroyed",(()=>{e.metaScene.destroyMetaModel(O)}))}const k=new Uint32Array(T);for(let e=0;e<R;e++){const t=w[e];void 0!==k[t]?k[t]++:k[t]=1}const V=u.vec3(),j=u.AABB3();for(let i=0;i<N;i++){const r=i===N-1,a=L[i],n=r?F:L[i+1],l=6*i,B=D.subarray(l,l+6);u.getAABB3Center(B,V),j[0]=B[0]-V[0],j[1]=B[1]-V[1],j[2]=B[2]-V[2],j[3]=B[3]-V[0],j[4]=B[4]-V[1],j[5]=B[5]-V[2];const R=Xe.createPositionsDecodeMatrix(j),O={};for(let r=a;r<n;r++){const a=o[C[r]],n=t.globalizeObjectIds?u.globalizeObjectId(s.id,a):a,l=r===F-1,D=S[r],L=l?w.length:S[r+1],B=[],N=e.metaScene.metaObjects[n],j={},z={};if(N){if(t.excludeTypesMap&&N.type&&t.excludeTypesMap[N.type])continue;if(t.includeTypesMap&&N.type&&!t.includeTypesMap[N.type])continue;const e=t.objectDefaults?t.objectDefaults[N.type]||t.objectDefaults.DEFAULT:null;e&&(!1===e.visible&&(j.visible=!1),!1===e.pickable&&(j.pickable=!1),e.colorize&&(z.color=e.colorize),void 0!==e.opacity&&null!==e.opacity&&(z.opacity=e.opacity),void 0!==e.metallic&&null!==e.metallic&&(z.metallic=e.metallic),void 0!==e.roughness&&null!==e.roughness&&(z.roughness=e.roughness))}else if(t.excludeUnclassifiedObjects)continue;for(let e=D;e<L;e++){const t=w[e],r=k[t]>1,o=t===T-1,a=Aa(A.subarray(6*e,6*e+3)),n=A[6*e+3]/255,l=A[6*e+4]/255,u=A[6*e+5]/255,C=I++;if(r){const r=E[e],w=g.slice(r,r+16),A="geometry."+i+"."+t;if(!O[A]){let e,i,r,a,n,l;switch(v[t]){case 0:e="solid",i=h.subarray(b[t],o?h.length:b[t+1]),r=c.subarray(P[t],o?c.length:P[t+1]),n=p.subarray(M[t],o?p.length:M[t+1]),l=_.subarray(x[t],o?_.length:x[t+1]);break;case 1:e="surface",i=h.subarray(b[t],o?h.length:b[t+1]),r=c.subarray(P[t],o?c.length:P[t+1]),n=p.subarray(M[t],o?p.length:M[t+1]),l=_.subarray(x[t],o?_.length:x[t+1]);break;case 2:e="points",i=h.subarray(b[t],o?h.length:b[t+1]),a=d.subarray(y[t],o?d.length:y[t+1]);break;case 3:e="lines",i=h.subarray(b[t],o?h.length:b[t+1]),n=p.subarray(M[t],o?p.length:M[t+1]);break;default:continue}s.createGeometry({id:A,rtcCenter:V,primitive:e,positions:i,normals:r,colors:a,indices:n,edgeIndices:l,positionsDecodeMatrix:m}),O[A]=!0}s.createMesh(f.apply(z,{id:C,geometryId:A,matrix:w,color:a,metallic:l,roughness:u,opacity:n})),B.push(C)}else{let e,i,r,g,m,w;switch(v[t]){case 0:e="solid",i=h.subarray(b[t],o?h.length:b[t+1]),r=c.subarray(P[t],o?c.length:P[t+1]),m=p.subarray(M[t],o?p.length:M[t+1]),w=_.subarray(x[t],o?_.length:x[t+1]);break;case 1:e="surface",i=h.subarray(b[t],o?h.length:b[t+1]),r=c.subarray(P[t],o?c.length:P[t+1]),m=p.subarray(M[t],o?p.length:M[t+1]),w=_.subarray(x[t],o?_.length:x[t+1]);break;case 2:e="points",i=h.subarray(b[t],o?h.length:b[t+1]),g=d.subarray(y[t],o?d.length:y[t+1]);break;case 3:e="lines",i=h.subarray(b[t],o?h.length:b[t+1]),m=p.subarray(M[t],o?p.length:M[t+1]);break;default:continue}s.createMesh(f.apply(z,{id:C,rtcCenter:V,primitive:e,positions:i,normals:r,colors:g,indices:m,edgeIndices:w,positionsDecodeMatrix:R,color:a,metallic:l,roughness:u,opacity:n})),B.push(C)}}B.length>0&&s.createEntity(f.apply(j,{id:n,isObject:!0,meshIds:B}))}}}(e,t,function(e){function t(e,t){return 0===e.length?[]:Ea.inflate(e,t).buffer}return{types:Ea.inflate(e.types,{to:"string"}),eachMetaObjectId:Ea.inflate(e.eachMetaObjectId,{to:"string"}),eachMetaObjectType:new Uint32Array(t(e.eachMetaObjectType)),eachMetaObjectName:Ea.inflate(e.eachMetaObjectName,{to:"string"}),eachMetaObjectParent:new Uint32Array(t(e.eachMetaObjectParent)),positions:new Uint16Array(t(e.positions)),normals:new Int8Array(t(e.normals)),colors:new Uint8Array(t(e.colors)),indices:new Uint32Array(t(e.indices)),edgeIndices:new Uint32Array(t(e.edgeIndices)),matrices:new Float32Array(t(e.matrices)),reusedGeometriesDecodeMatrix:new Float32Array(t(e.reusedGeometriesDecodeMatrix)),eachGeometryPrimitiveType:new Uint8Array(t(e.eachGeometryPrimitiveType)),eachGeometryPositionsPortion:new Uint32Array(t(e.eachGeometryPositionsPortion)),eachGeometryNormalsPortion:new Uint32Array(t(e.eachGeometryNormalsPortion)),eachGeometryColorsPortion:new Uint32Array(t(e.eachGeometryColorsPortion)),eachGeometryIndicesPortion:new Uint32Array(t(e.eachGeometryIndicesPortion)),eachGeometryEdgeIndicesPortion:new Uint32Array(t(e.eachGeometryEdgeIndicesPortion)),eachMeshGeometriesPortion:new Uint32Array(t(e.eachMeshGeometriesPortion)),eachMeshMatricesPortion:new Uint32Array(t(e.eachMeshMatricesPortion)),eachMeshMaterial:new Uint8Array(t(e.eachMeshMaterial)),eachEntityMetaObject:new Uint32Array(t(e.eachEntityMetaObject)),eachEntityMeshesPortion:new Uint32Array(t(e.eachEntityMeshesPortion)),eachTileAABB:new Float64Array(t(e.eachTileAABB)),eachTileEntitiesPortion:new Uint32Array(t(e.eachTileEntitiesPortion))}}(function(e){return{types:e[0],eachMetaObjectId:e[1],eachMetaObjectType:e[2],eachMetaObjectName:e[3],eachMetaObjectParent:e[4],positions:e[5],normals:e[6],colors:e[7],indices:e[8],edgeIndices:e[9],matrices:e[10],reusedGeometriesDecodeMatrix:e[11],eachGeometryPrimitiveType:e[12],eachGeometryPositionsPortion:e[13],eachGeometryNormalsPortion:e[14],eachGeometryColorsPortion:e[15],eachGeometryIndicesPortion:e[16],eachGeometryEdgeIndicesPortion:e[17],eachMeshGeometriesPortion:e[18],eachMeshMatricesPortion:e[19],eachMeshMaterial:e[20],eachEntityMetaObject:e[21],eachEntityMeshesPortion:e[22],eachTileAABB:e[23],eachTileEntitiesPortion:e[24]}}(i)),s)}},Sa={};Sa[aa.version]=aa,Sa[ha.version]=ha,Sa[da.version]=da,Sa[fa.version]=fa,Sa[va.version]=va,Sa[ya.version]=ya,Sa[wa.version]=wa,Sa[Ca.version]=Ca;class Da extends a{constructor(e,t={}){super("XKTLoader",e,t),this._maxGeometryBatchSize=t.maxGeometryBatchSize,this.dataSource=t.dataSource,this.objectDefaults=t.objectDefaults,this.includeTypes=t.includeTypes,this.excludeTypes=t.excludeTypes,this.excludeUnclassifiedObjects=t.excludeUnclassifiedObjects}get supportedVersions(){return Object.keys(Sa)}set dataSource(e){this._dataSource=e||new ia}get dataSource(){return this._dataSource}set objectDefaults(e){this._objectDefaults=e||Vo}get objectDefaults(){return this._objectDefaults}set includeTypes(e){this._includeTypes=e}get includeTypes(){return this._includeTypes}set excludeTypes(e){this._excludeTypes=e}get excludeTypes(){return this._excludeTypes}set excludeUnclassifiedObjects(e){this._excludeUnclassifiedObjects=!!e}get excludeUnclassifiedObjects(){return this._excludeUnclassifiedObjects}set globalizeObjectIds(e){this._globalizeObjectIds=!!e}get globalizeObjectIds(){return this._globalizeObjectIds}load(e={}){e.id&&this.viewer.scene.components[e.id]&&(this.error("Component with this ID already exists in viewer: "+e.id+" - will autogenerate this ID"),delete e.id);const t=new Po(this.viewer.scene,f.apply(e,{isModel:!0,maxGeometryBatchSize:this._maxGeometryBatchSize})),i=t.id;if(!e.src&&!e.xkt)return this.error("load() param expected: src or xkt"),t;const s={},r=e.includeTypes||this._includeTypes,o=e.excludeTypes||this._excludeTypes,a=e.objectDefaults||this._objectDefaults;if(r){s.includeTypesMap={};for(let e=0,t=r.length;e<t;e++)s.includeTypesMap[r[e]]=!0}if(o){s.excludeTypesMap={};for(let e=0,t=o.length;e<t;e++)s.excludeTypesMap[o[e]]=!0}if(a&&(s.objectDefaults=a),s.excludeUnclassifiedObjects=void 0!==e.excludeUnclassifiedObjects?!!e.excludeUnclassifiedObjects:this._excludeUnclassifiedObjects,s.globalizeObjectIds=void 0!==e.globalizeObjectIds?!!e.globalizeObjectIds:this._globalizeObjectIds,e.metaModelSrc||e.metaModelData){const a=a=>!!this.viewer.metaScene.createMetaModel(i,a,{includeTypes:r,excludeTypes:o,globalizeObjectIds:this.globalizeObjectIds})&&(e.src?this._loadModel(e.src,e,s,t):this._parseModel(e.xkt,e,s,t),t.once("destroyed",(()=>{this.viewer.metaScene.destroyMetaModel(t.id)})),!0);if(e.metaModelSrc){const s=e.metaModelSrc;this.viewer.scene.canvas.spinner.processes++,this._dataSource.getMetaModel(s,(e=>{t.destroyed||(a(e)||(this.error(`load(): Failed to load model metadata for model '${i} from '${s}' - metadata not valid`),t.fire("error","Metadata not valid")),this.viewer.scene.canvas.spinner.processes--)}),(e=>{this.error(`load(): Failed to load model metadata for model '${i} from  '${s}' - ${e}`),t.fire("error",`Failed to load model metadata from  '${s}' - ${e}`),this.viewer.scene.canvas.spinner.processes--}))}else e.metaModelData&&(a(e.metaModelData)||(this.error(`load(): Failed to load model metadata for model '${i} from '${metaModelSrc}' - metadata not valid`),t.fire("error","Metadata not valid")))}else e.src?this._loadModel(e.src,e,s,t):this._parseModel(e.xkt,e,s,t);return t}_loadModel(e,t,i,s){const r=this.viewer.scene.canvas.spinner;r.processes++,this._dataSource.getXKT(t.src,(e=>{this._parseModel(e,t,i,s),r.processes--}),(e=>{r.processes--,this.error(e),s.fire("error",e)}))}_parseModel(e,t,i,s){if(s.destroyed)return;const r=new DataView(e),o=new Uint8Array(e),a=r.getUint32(0,!0),n=Sa[a];if(!n)return void this.error("Unsupported .XKT file version: "+a+" - this XKTLoaderPlugin supports versions "+Object.keys(Sa));this.log("Loading .xkt V"+a);const l=r.getUint32(4,!0),h=[];let c=4*(l+2);for(let e=0;e<l;e++){const t=r.getUint32(4*(e+2),!0);h.push(o.subarray(c,c+t)),c+=t}n.parse(this.viewer,i,h,s),s.finalize(),s.scene.once("tick",(()=>{s.destroyed||(s.scene.fire("modelLoaded",s.id),s.fire("loaded",!0,!1))}))}}var La={};!function(e){var t,i="File format is not recognized.",s="Error while reading zip file.",r="Error while reading file data.",o=524288,a="text/plain";try{t=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function n(){this.crc=-1}function l(){}function h(e,t){var i,s;return i=new ArrayBuffer(e),s=new Uint8Array(i),t&&s.set(t,0),{buffer:i,array:s,view:new DataView(i)}}function c(){}function u(e){var t,i=this;i.size=0,i.init=function(s,r){var o=new Blob([e],{type:a});(t=new p(o)).init((function(){i.size=t.size,s()}),r)},i.readUint8Array=function(e,i,s,r){t.readUint8Array(e,i,s,r)}}function d(t){var i,s=this;s.size=0,s.init=function(e){for(var r=t.length;"="==t.charAt(r-1);)r--;i=t.indexOf(",")+1,s.size=Math.floor(.75*(r-i)),e()},s.readUint8Array=function(s,r,o){var a,n=h(r),l=4*Math.floor(s/3),c=4*Math.ceil((s+r)/3),u=e.atob(t.substring(l+i,c+i)),d=s-3*Math.floor(l/4);for(a=d;a<d+r;a++)n.array[a-d]=u.charCodeAt(a);o(n.array)}}function p(e){var t=this;t.size=0,t.init=function(i){t.size=e.size,i()},t.readUint8Array=function(t,i,s,r){var o=new FileReader;o.onload=function(e){s(new Uint8Array(e.target.result))},o.onerror=r;try{o.readAsArrayBuffer(function(e,t,i){if(t<0||i<0||t+i>e.size)throw new RangeError("offset:"+t+", length:"+i+", size:"+e.size);return e.slice?e.slice(t,t+i):e.webkitSlice?e.webkitSlice(t,t+i):e.mozSlice?e.mozSlice(t,t+i):e.msSlice?e.msSlice(t,t+i):void 0}(e,t,i))}catch(e){r(e)}}}function _(){}function f(e){var i,s=this;s.init=function(e){i=new Blob([],{type:a}),e()},s.writeUint8Array=function(e,s){i=new Blob([i,t?e:e.buffer],{type:a}),s()},s.getData=function(t,s){var r=new FileReader;r.onload=function(e){t(e.target.result)},r.onerror=s,r.readAsText(i,e)}}function g(t){var i=this,s="",r="";i.init=function(e){s+="data:"+(t||"")+";base64,",e()},i.writeUint8Array=function(t,i){var o,a=r.length,n=r;for(r="",o=0;o<3*Math.floor((a+t.length)/3)-a;o++)n+=String.fromCharCode(t[o]);for(;o<t.length;o++)r+=String.fromCharCode(t[o]);n.length>2?s+=e.btoa(n):r=n,i()},i.getData=function(t){t(s+e.btoa(r))}}function m(e){var i,s=this;s.init=function(t){i=new Blob([],{type:e}),t()},s.writeUint8Array=function(s,r){i=new Blob([i,t?s:s.buffer],{type:e}),r()},s.getData=function(e){e(i)}}function v(e,t,i,s,r,a,n,l,h,c){var u,d,p,_=0,f=t.sn;function g(){e.removeEventListener("message",m,!1),l(d,p)}function m(t){var i=t.data,r=i.data,o=i.error;if(o)return o.toString=function(){return"Error: "+this.message},void h(o);if(i.sn===f)switch("number"==typeof i.codecTime&&(e.codecTime+=i.codecTime),"number"==typeof i.crcTime&&(e.crcTime+=i.crcTime),i.type){case"append":r?(d+=r.length,s.writeUint8Array(r,(function(){v()}),c)):v();break;case"flush":p=i.crc,r?(d+=r.length,s.writeUint8Array(r,(function(){g()}),c)):g();break;case"progress":n&&n(u+i.loaded,a);break;case"importScripts":case"newTask":case"echo":break;default:console.warn("zip.js:launchWorkerProcess: unknown message: ",i)}}function v(){(u=_*o)<=a?i.readUint8Array(r+u,Math.min(o,a-u),(function(i){n&&n(u,a);var s=0===u?t:{sn:f};s.type="append",s.data=i;try{e.postMessage(s,[i.buffer])}catch(t){e.postMessage(s)}_++}),h):e.postMessage({sn:f,type:"flush"})}d=0,e.addEventListener("message",m,!1),v()}function b(e,t,i,s,r,a,l,h,c,u){var d,p=0,_=0,f="input"===a,g="output"===a,m=new n;!function a(){var n;if((d=p*o)<r)t.readUint8Array(s+d,Math.min(o,r-d),(function(t){var s;try{s=e.append(t,(function(e){l&&l(d+e,r)}))}catch(e){return void c(e)}s?(_+=s.length,i.writeUint8Array(s,(function(){p++,setTimeout(a,1)}),u),g&&m.append(s)):(p++,setTimeout(a,1)),f&&m.append(t),l&&l(d,r)}),c);else{try{n=e.flush()}catch(e){return void c(e)}n?(g&&m.append(n),_+=n.length,i.writeUint8Array(n,(function(){h(_,m.get())}),u)):h(_,m.get())}}()}function P(t,i,s,r,o,a,n,h,c,u,d){var p="input";e.zip.useWebWorkers&&n?v(t,{sn:i,codecClass:"NOOP",crcType:p},s,r,o,a,c,h,u,d):b(new l,s,r,o,a,p,c,h,u,d)}function y(e){var t,i,s="",r=["Ç","ü","é","â","ä","à","å","ç","ê","ë","è","ï","î","ì","Ä","Å","É","æ","Æ","ô","ö","ò","û","ù","ÿ","Ö","Ü","ø","£","Ø","×","ƒ","á","í","ó","ú","ñ","Ñ","ª","º","¿","®","¬","½","¼","¡","«","»","_","_","_","¦","¦","Á","Â","À","©","¦","¦","+","+","¢","¥","+","+","-","-","+","-","+","ã","Ã","+","+","-","-","¦","-","+","¤","ð","Ð","Ê","Ë","È","i","Í","Î","Ï","+","+","_","_","¦","Ì","_","Ó","ß","Ô","Ò","õ","Õ","µ","þ","Þ","Ú","Û","Ù","ý","Ý","¯","´","­","±","_","¾","¶","§","÷","¸","°","¨","·","¹","³","²","_"," "];for(t=0;t<e.length;t++)s+=(i=255&e.charCodeAt(t))>127?r[i-128]:String.fromCharCode(i);return s}function M(e){return decodeURIComponent(escape(e))}function x(e){var t,i="";for(t=0;t<e.length;t++)i+=String.fromCharCode(e[t]);return i}function w(e,t,i,s,r){e.version=t.view.getUint16(i,!0),e.bitFlag=t.view.getUint16(i+2,!0),e.compressionMethod=t.view.getUint16(i+4,!0),e.lastModDateRaw=t.view.getUint32(i+6,!0),e.lastModDate=function(e){var t=(4294901760&e)>>16,i=65535&e;try{return new Date(1980+((65024&t)>>9),((480&t)>>5)-1,31&t,(63488&i)>>11,(2016&i)>>5,2*(31&i),0)}catch(e){}}(e.lastModDateRaw),1!=(1&e.bitFlag)?((s||8!=(8&e.bitFlag))&&(e.crc32=t.view.getUint32(i+10,!0),e.compressedSize=t.view.getUint32(i+14,!0),e.uncompressedSize=t.view.getUint32(i+18,!0)),4294967295!==e.compressedSize&&4294967295!==e.uncompressedSize?(e.filenameLength=t.view.getUint16(i+22,!0),e.extraFieldLength=t.view.getUint16(i+24,!0)):r("File is using Zip64 (4gb+ file size).")):r("File contains encrypted entry.")}function E(t,o,a){var n=0;function l(){}l.prototype.getData=function(s,o,l,c){var u=this;function d(e,t){c&&!function(e){var t=h(4);return t.view.setUint32(0,e),u.crc32==t.view.getUint32(0)}(t)?a("CRC failed."):s.getData((function(e){o(e)}))}function p(e){a(e||r)}function _(e){a(e||"Error while writing file data.")}t.readUint8Array(u.offset,30,(function(r){var o,f=h(r.length,r);1347093252==f.view.getUint32(0)?(w(u,f,4,!1,a),o=u.offset+30+u.filenameLength+u.extraFieldLength,s.init((function(){0===u.compressionMethod?P(u._worker,n++,t,s,o,u.compressedSize,c,d,l,p,_):function(t,i,s,r,o,a,n,l,h,c,u){var d=n?"output":"none";e.zip.useWebWorkers?v(t,{sn:i,codecClass:"Inflater",crcType:d},s,r,o,a,h,l,c,u):b(new e.zip.Inflater,s,r,o,a,d,h,l,c,u)}(u._worker,n++,t,s,o,u.compressedSize,c,d,l,p,_)}),_)):a(i)}),p)};var c={getEntries:function(e){var r=this._worker;!function(e){function r(i,r){t.readUint8Array(t.size-i,i,(function(t){for(var i=t.length-22;i>=0;i--)if(80===t[i]&&75===t[i+1]&&5===t[i+2]&&6===t[i+3])return void e(new DataView(t.buffer,i,22));r()}),(function(){a(s)}))}t.size<22?a(i):r(22,(function(){r(Math.min(65558,t.size),(function(){a(i)}))}))}((function(o){var n,c;n=o.getUint32(16,!0),c=o.getUint16(8,!0),n<0||n>=t.size?a(i):t.readUint8Array(n,t.size-n,(function(t){var s,o,n,u,d=0,p=[],_=h(t.length,t);for(s=0;s<c;s++){if((o=new l)._worker=r,1347092738!=_.view.getUint32(d))return void a(i);w(o,_,d+6,!0,a),o.commentLength=_.view.getUint16(d+32,!0),o.directory=16==(16&_.view.getUint8(d+38)),o.offset=_.view.getUint32(d+42,!0),n=x(_.array.subarray(d+46,d+46+o.filenameLength)),o.filename=2048==(2048&o.bitFlag)?M(n):y(n),o.directory||"/"!=o.filename.charAt(o.filename.length-1)||(o.directory=!0),u=x(_.array.subarray(d+46+o.filenameLength+o.extraFieldLength,d+46+o.filenameLength+o.extraFieldLength+o.commentLength)),o.comment=2048==(2048&o.bitFlag)?M(u):y(u),p.push(o),d+=46+o.filenameLength+o.extraFieldLength+o.commentLength}e(p)}),(function(){a(s)}))}))},close:function(e){this._worker&&(this._worker.terminate(),this._worker=null),e&&e()},_worker:null};e.zip.useWebWorkers?L("inflater",(function(e){c._worker=e,o(c)}),(function(e){a(e)})):o(c)}function A(e){return unescape(encodeURIComponent(e))}function C(e){var t,i=[];for(t=0;t<e.length;t++)i.push(e.charCodeAt(t));return i}function S(t,i,s,o){var a={},n=[],l=0,c=0;function u(e){s(e||"Error while writing zip file.")}function d(e){s(e||r)}var p={add:function(i,r,p,_,f){var g,m,y,M=this._worker;function x(e,i){var s=h(16);l+=e||0,s.view.setUint32(0,1347094280),void 0!==i&&(g.view.setUint32(10,i,!0),s.view.setUint32(4,i,!0)),r&&(s.view.setUint32(8,e,!0),g.view.setUint32(14,e,!0),s.view.setUint32(12,r.size,!0),g.view.setUint32(18,r.size,!0)),t.writeUint8Array(s.array,(function(){l+=16,p()}),u)}function w(){f=f||{},i=i.trim(),f.directory&&"/"!=i.charAt(i.length-1)&&(i+="/"),a.hasOwnProperty(i)?s("File already exists."):(m=C(A(i)),n.push(i),function(e){var s;y=f.lastModDate||new Date,g=h(26),a[i]={headerArray:g.array,directory:f.directory,filename:m,offset:l,comment:C(A(f.comment||""))},g.view.setUint32(0,335546376),f.version&&g.view.setUint8(0,f.version),o||0===f.level||f.directory||g.view.setUint16(4,2048),g.view.setUint16(6,(y.getHours()<<6|y.getMinutes())<<5|y.getSeconds()/2,!0),g.view.setUint16(8,(y.getFullYear()-1980<<4|y.getMonth()+1)<<5|y.getDate(),!0),g.view.setUint16(22,m.length,!0),(s=h(30+m.length)).view.setUint32(0,1347093252),s.array.set(g.array,4),s.array.set(m,30),l+=s.array.length,t.writeUint8Array(s.array,e,u)}((function(){r?o||0===f.level?P(M,c++,r,t,0,r.size,!0,x,_,d,u):function(t,i,s,r,o,a,n,l,h){var c="input";e.zip.useWebWorkers?v(t,{sn:i,options:{level:o},codecClass:"Deflater",crcType:c},s,r,0,s.size,n,a,l,h):b(new e.zip.Deflater,s,r,0,s.size,c,n,a,l,h)}(M,c++,r,t,f.level,x,_,d,u):x()})))}r?r.init(w,d):w()},close:function(e){this._worker&&(this._worker.terminate(),this._worker=null);var i,s,r,o=0,c=0;for(s=0;s<n.length;s++)o+=46+(r=a[n[s]]).filename.length+r.comment.length;for(i=h(o+22),s=0;s<n.length;s++)r=a[n[s]],i.view.setUint32(c,1347092738),i.view.setUint16(c+4,5120),i.array.set(r.headerArray,c+6),i.view.setUint16(c+32,r.comment.length,!0),r.directory&&i.view.setUint8(c+38,16),i.view.setUint32(c+42,r.offset,!0),i.array.set(r.filename,c+46),i.array.set(r.comment,c+46+r.filename.length),c+=46+r.filename.length+r.comment.length;i.view.setUint32(c,1347093766),i.view.setUint16(c+8,n.length,!0),i.view.setUint16(c+10,n.length,!0),i.view.setUint32(c+12,o,!0),i.view.setUint32(c+16,l,!0),t.writeUint8Array(i.array,(function(){t.getData(e)}),u)},_worker:null};e.zip.useWebWorkers?L("deflater",(function(e){p._worker=e,i(p)}),(function(e){s(e)})):i(p)}n.prototype.append=function(e){for(var t=0|this.crc,i=this.table,s=0,r=0|e.length;s<r;s++)t=t>>>8^i[255&(t^e[s])];this.crc=t},n.prototype.get=function(){return~this.crc},n.prototype.table=function(){var e,t,i,s=[];for(e=0;e<256;e++){for(i=e,t=0;t<8;t++)1&i?i=i>>>1^3988292384:i>>>=1;s[e]=i}return s}(),l.prototype.append=function(e,t){return e},l.prototype.flush=function(){},u.prototype=new c,u.prototype.constructor=u,d.prototype=new c,d.prototype.constructor=d,p.prototype=new c,p.prototype.constructor=p,_.prototype.getData=function(e){e(this.data)},f.prototype=new _,f.prototype.constructor=f,g.prototype=new _,g.prototype.constructor=g,m.prototype=new _,m.prototype.constructor=m;var D={deflater:["z-worker.js","deflate.js"],inflater:["z-worker.js","inflate.js"]};function L(t,i,s){if(null===e.zip.workerScripts||null===e.zip.workerScriptsPath){var r,o,a;if(e.zip.workerScripts){if(r=e.zip.workerScripts[t],!Array.isArray(r))return void s(new Error("zip.workerScripts."+t+" is not an array!"));o=r,a=document.createElement("a"),r=o.map((function(e){return a.href=e,a.href}))}else(r=D[t].slice(0))[0]=(e.zip.workerScriptsPath||"")+r[0];var n=new Worker(r[0]);n.codecTime=n.crcTime=0,n.postMessage({type:"importScripts",scripts:r.slice(1)}),n.addEventListener("message",(function e(t){var r=t.data;if(r.error)return n.terminate(),void s(r.error);"importScripts"===r.type&&(n.removeEventListener("message",e),n.removeEventListener("error",l),i(n))})),n.addEventListener("error",l)}else s(new Error("Either zip.workerScripts or zip.workerScriptsPath may be set, not both."));function l(e){n.terminate(),s(e)}}function B(e){console.error(e)}e.zip={Reader:c,Writer:_,BlobReader:p,Data64URIReader:d,TextReader:u,BlobWriter:m,Data64URIWriter:g,TextWriter:f,createReader:function(e,t,i){i=i||B,e.init((function(){E(e,t,i)}),i)},createWriter:function(e,t,i,s){i=i||B,s=!!s,e.init((function(){S(e,t,i,s)}),i)},useWebWorkers:!0,workerScriptsPath:null,workerScripts:null}}(La);!function(e){var t,i,s=e.Reader,r=e.Writer;try{i=0===new Blob([new DataView(new ArrayBuffer(0))]).size}catch(e){}function o(e){var t=this;function i(i,s){var r;t.data?i():((r=new XMLHttpRequest).addEventListener("load",(function(){t.size||(t.size=Number(r.getResponseHeader("Content-Length"))||Number(r.response.byteLength)),t.data=new Uint8Array(r.response),i()}),!1),r.addEventListener("error",s,!1),r.open("GET",e),r.responseType="arraybuffer",r.send())}t.size=0,t.init=function(s,r){if(function(e){var t=document.createElement("a");return t.href=e,"http:"===t.protocol||"https:"===t.protocol}(e)){var o=new XMLHttpRequest;o.addEventListener("load",(function(){t.size=Number(o.getResponseHeader("Content-Length")),t.size?s():i(s,r)}),!1),o.addEventListener("error",r,!1),o.open("HEAD",e),o.send()}else i(s,r)},t.readUint8Array=function(e,s,r,o){i((function(){r(new Uint8Array(t.data.subarray(e,e+s)))}),o)}}function a(e){var t=this;t.size=0,t.init=function(i,s){var r=new XMLHttpRequest;r.addEventListener("load",(function(){t.size=Number(r.getResponseHeader("Content-Length")),"bytes"==r.getResponseHeader("Accept-Ranges")?i():s("HTTP Range not supported.")}),!1),r.addEventListener("error",s,!1),r.open("HEAD",e),r.send()},t.readUint8Array=function(t,i,s,r){!function(t,i,s,r){var o=new XMLHttpRequest;o.open("GET",e),o.responseType="arraybuffer",o.setRequestHeader("Range","bytes="+t+"-"+(t+i-1)),o.addEventListener("load",(function(){s(o.response)}),!1),o.addEventListener("error",r,!1),o.send()}(t,i,(function(e){s(new Uint8Array(e))}),r)}}function n(e){var t=this;t.size=0,t.init=function(i,s){t.size=e.byteLength,i()},t.readUint8Array=function(t,i,s,r){s(new Uint8Array(e.slice(t,t+i)))}}function l(){var e,t=this;t.init=function(t,i){e=new Uint8Array,t()},t.writeUint8Array=function(t,i,s){var r=new Uint8Array(e.length+t.length);r.set(e),r.set(t,e.length),e=r,i()},t.getData=function(t){t(e.buffer)}}function h(e,t){var s,r=this;r.init=function(t,i){e.createWriter((function(e){s=e,t()}),i)},r.writeUint8Array=function(e,r,o){var a=new Blob([i?e:e.buffer],{type:t});s.onwrite=function(){s.onwrite=null,r()},s.onerror=o,s.write(a)},r.getData=function(t){e.file(t)}}o.prototype=new s,o.prototype.constructor=o,a.prototype=new s,a.prototype.constructor=a,n.prototype=new s,n.prototype.constructor=n,l.prototype=new r,l.prototype.constructor=l,h.prototype=new r,h.prototype.constructor=h,e.FileWriter=h,e.HttpReader=o,e.HttpRangeReader=a,e.ArrayBufferReader=n,e.ArrayBufferWriter=l,e.fs&&((t=e.fs.ZipDirectoryEntry).prototype.addHttpContent=function(t,i,s){return function(t,i,s,r){if(t.directory)return new e.fs.ZipFileEntry(t.fs,i,s,t);throw"Parent entry is not a directory."}(this,t,{data:i,Reader:s?a:o})},t.prototype.importHttpContent=function(e,t,i,s){this.importZip(t?new a(e):new o(e),i,s)},e.fs.FS.prototype.importHttpContent=function(e,i,s,r){this.entries=[],this.root=new t(this),this.root.importHttpContent(e,i,s,r)})}(La.zip);u.vec3();const Ba=u.vec3(),Ta=u.vec3(),Ra=u.vec3(),Fa=u.vec3(),Na=u.vec3();class Ia extends A{get type(){return"CameraFlightAnimation"}constructor(e,t={}){super(e,t),this._look1=u.vec3(),this._eye1=u.vec3(),this._up1=u.vec3(),this._look2=u.vec3(),this._eye2=u.vec3(),this._up2=u.vec3(),this._orthoScale1=1,this._orthoScale2=1,this._flying=!1,this._flyEyeLookUp=!1,this._flyingEye=!1,this._flyingLook=!1,this._callback=null,this._callbackScope=null,this._time1=null,this._time2=null,this.easing=!1!==t.easing,this.duration=t.duration,this.fit=t.fit,this.fitFOV=t.fitFOV,this.trail=t.trail}flyTo(e,t,i){e=e||this.scene,this._flying&&this.stop(),this._flying=!1,this._flyingEye=!1,this._flyingLook=!1,this._flyingEyeLookUp=!1,this._callback=t,this._callbackScope=i;const s=this.scene.camera,r=!!e.projection&&e.projection!==s.projection;let o,a,n,l,h;if(this._eye1[0]=s.eye[0],this._eye1[1]=s.eye[1],this._eye1[2]=s.eye[2],this._look1[0]=s.look[0],this._look1[1]=s.look[1],this._look1[2]=s.look[2],this._up1[0]=s.up[0],this._up1[1]=s.up[1],this._up1[2]=s.up[2],this._orthoScale1=s.ortho.scale,this._orthoScale2=e.orthoScale||this._orthoScale1,e.aabb)o=e.aabb;else if(6===e.length)o=e;else if(e.eye&&e.look||e.up)a=e.eye,n=e.look,l=e.up;else if(e.eye)a=e.eye;else if(e.look)n=e.look;else{let s=e;if((f.isNumeric(s)||f.isString(s))&&(h=s,s=this.scene.components[h],!s))return this.error("Component not found: "+f.inQuotes(h)),void(t&&(i?t.call(i):t()));r||(o=s.aabb||this.scene.aabb)}const c=e.poi;if(o){if(o[3]<o[0]||o[4]<o[1]||o[5]<o[2])return;if(o[3]===o[0]&&o[4]===o[1]&&o[5]===o[2])return;o=o.slice();const t=u.getAABB3Center(o);this._look2=c||t;const i=u.subVec3(this._eye1,this._look1,Ba),s=u.normalizeVec3(i),r=c?u.getAABB3DiagPoint(o,c):u.getAABB3Diag(o),a=e.fitFOV||this._fitFOV,n=Math.abs(r/Math.tan(a*u.DEGTORAD));this._orthoScale2=1.1*r,this._eye2[0]=this._look2[0]+s[0]*n,this._eye2[1]=this._look2[1]+s[1]*n,this._eye2[2]=this._look2[2]+s[2]*n,this._up2[0]=this._up1[0],this._up2[1]=this._up1[1],this._up2[2]=this._up1[2],this._flyingEyeLookUp=!0}else(a||n||l)&&(this._flyingEyeLookUp=!!a&&!!n&&!!l,this._flyingEye=!!a&&!n,this._flyingLook=!!n&&!a,a&&(this._eye2[0]=a[0],this._eye2[1]=a[1],this._eye2[2]=a[2]),n&&(this._look2[0]=n[0],this._look2[1]=n[1],this._look2[2]=n[2]),l&&(this._up2[0]=l[0],this._up2[1]=l[1],this._up2[2]=l[2]));r?("ortho"===e.projection&&"ortho"!==s.projection&&(this._projection2="ortho",this._projMatrix1=s.projMatrix.slice(),s.ortho.scale=this._orthoScale2,this._projMatrix2=s.ortho.matrix.slice(),s.projection="customProjection"),"perspective"===e.projection&&"perspective"!==s.projection&&(this._projection2="perspective",this._projMatrix1=s.projMatrix.slice(),this._projMatrix2=s.perspective.matrix.slice(),s.projection="customProjection")):this._projection2=null,this.fire("started",e,!0),this._time1=Date.now(),this._time2=this._time1+(e.duration?1e3*e.duration:this._duration),this._flying=!0,w.scheduleTask(this._update,this)}jumpTo(e){this._jumpTo(e)}_jumpTo(e){this._flying&&this.stop();const t=this.scene.camera;var i,s,r,o,a;if(e.aabb)i=e.aabb;else if(6===e.length)i=e;else if(e.eye||e.look||e.up)r=e.eye,o=e.look,a=e.up;else{let t=e;if((f.isNumeric(t)||f.isString(t))&&(s=t,t=this.scene.components[s],!t))return void this.error("Component not found: "+f.inQuotes(s));i=t.aabb||this.scene.aabb}const n=e.poi;if(i){if(i[3]<=i[0]||i[4]<=i[1]||i[5]<=i[2])return;var l=n?u.getAABB3DiagPoint(i,n):u.getAABB3Diag(i);let s;o=n||u.getAABB3Center(i,o),this._trail?u.subVec3(t.look,o,Na):u.subVec3(t.eye,t.look,Na),u.normalizeVec3(Na),s=(void 0!==e.fit?e.fit:this._fit)?Math.abs(l/Math.tan((e.fitFOV||this._fitFOV)*u.DEGTORAD)):u.lenVec3(u.subVec3(t.eye,t.look,Ba)),u.mulVec3Scalar(Na,s),t.eye=u.addVec3(o,Na,Ba),t.look=o,this.scene.camera.ortho.scale=1.1*l}else(r||o||a)&&(r&&(t.eye=r),o&&(t.look=o),a&&(t.up=a));e.projection&&(t.projection=e.projection)}_update(){if(!this._flying)return;let e=(Date.now()-this._time1)/(this._time2-this._time1);const t=e>=1;e>1&&(e=1);const i=this.easing?Ia._ease(e,0,1,1):e,s=this.scene.camera;if(this._flyingEye||this._flyingLook?this._flyingEye?(u.subVec3(s.eye,s.look,Na),s.eye=u.lerpVec3(i,0,1,this._eye1,this._eye2,Ra),s.look=u.subVec3(Ra,Na,Ta)):this._flyingLook&&(s.look=u.lerpVec3(i,0,1,this._look1,this._look2,Ta),s.up=u.lerpVec3(i,0,1,this._up1,this._up2,Fa)):this._flyingEyeLookUp&&(s.eye=u.lerpVec3(i,0,1,this._eye1,this._eye2,Ra),s.look=u.lerpVec3(i,0,1,this._look1,this._look2,Ta),s.up=u.lerpVec3(i,0,1,this._up1,this._up2,Fa)),this._projection2){const t="ortho"===this._projection2?Ia._easeOutExpo(e,0,1,1):Ia._easeInCubic(e,0,1,1);s.customProjection.matrix=u.lerpMat4(t,0,1,this._projMatrix1,this._projMatrix2)}else s.ortho.scale=this._orthoScale1+e*(this._orthoScale2-this._orthoScale1);t?this.stop():w.scheduleTask(this._update,this)}static _ease(e,t,i,s){return-i*(e/=s)*(e-2)+t}static _easeInCubic(e,t,i,s){return i*(e/=s)*e*e+t}static _easeOutExpo(e,t,i,s){return i*(1-Math.pow(2,-10*e/s))+t}stop(){if(!this._flying)return;this._flying=!1,this._time1=null,this._time2=null,this._projection2&&(this.scene.camera.projection=this._projection2);const e=this._callback;e&&(this._callback=null,this._callbackScope?e.call(this._callbackScope):e()),this.fire("stopped",!0,!0)}cancel(){this._flying&&(this._flying=!1,this._time1=null,this._time2=null,this._callback&&(this._callback=null),this.fire("canceled",!0,!0))}set duration(e){this._duration=e?1e3*e:500,this.stop()}get duration(){return this._duration/1e3}set fit(e){this._fit=!1!==e}get fit(){return this._fit}set fitFOV(e){this._fitFOV=e||45}get fitFOV(){return this._fitFOV}set trail(e){this._trail=!!e}get trail(){return this._trail}destroy(){this.stop(),super.destroy()}}var Oa={load:function(e,t){var i=new XMLHttpRequest;i.open("GET",e,!0),i.responseType="arraybuffer",i.onload=function(e){t(e.target.response)},i.send()},save:function(e,t){var i="data:application/octet-stream;base64,"+btoa(Oa.parse._buffToStr(e));window.location.href=i},clone:function(e){return JSON.parse(JSON.stringify(e))},bin:{}};Oa.bin.f=new Float32Array(1),Oa.bin.fb=new Uint8Array(Oa.bin.f.buffer),Oa.bin.rf=function(e,t){for(var i=Oa.bin.f,s=Oa.bin.fb,r=0;r<4;r++)s[r]=e[t+r];return i[0]},Oa.bin.rsl=function(e,t){return e[t]|e[t+1]<<8},Oa.bin.ril=function(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24},Oa.bin.rASCII0=function(e,t){for(var i="";0!=e[t];)i+=String.fromCharCode(e[t++]);return i},Oa.bin.wf=function(e,t,i){new Float32Array(e.buffer,t,1)[0]=i},Oa.bin.wsl=function(e,t,i){e[t]=i,e[t+1]=i>>8},Oa.bin.wil=function(e,t,i){e[t]=i,e[t+1]=i>>8,e[t+2]=i>>16,e[t+3]},Oa.parse={},Oa.parse._buffToStr=function(e){for(var t=new Uint8Array(e),i="",s=0;s<t.length;s++)i=i.concat(String.fromCharCode(t[s]));return i},Oa.parse._strToBuff=function(e){for(var t=new ArrayBuffer(e.length),i=new Uint8Array(t),s=0;s<e.length;s++)i[s]=e.charCodeAt(s);return t},Oa.parse._readLine=function(e,t){for(var i="";10!=e[t];)i+=String.fromCharCode(e[t++]);return i},Oa.parse.fromJSON=function(e){return JSON.parse(Oa.parse._buffToStr(e))},Oa.parse.toJSON=function(e){var t=JSON.stringify(e);return Oa.parse._strToBuff(t)},Oa.parse.fromOBJ=function(e){for(var t={groups:{},c_verts:[],c_uvt:[],c_norms:[],i_verts:[],i_uvt:[],i_norms:[]},i={from:0,to:0},s=0,r=new Uint8Array(e);s<r.length;){var o=Oa.parse._readLine(r,s);s+=o.length+1;var a=(o=(o=o.replace(/ +(?= )/g,"")).replace(/(^\s+|\s+$)/g,"")).split(" ");if("g"==a[0]&&(i.to=t.i_verts.length,null==t.groups[a[1]]&&(t.groups[a[1]]={from:t.i_verts.length,to:0}),i=t.groups[a[1]]),"v"==a[0]){var n=parseFloat(a[1]),l=parseFloat(a[2]),h=parseFloat(a[3]);t.c_verts.push(n,l,h)}if("vt"==a[0]&&(n=parseFloat(a[1]),l=1-parseFloat(a[2]),t.c_uvt.push(n,l)),"vn"==a[0]&&(n=parseFloat(a[1]),l=parseFloat(a[2]),h=parseFloat(a[3]),t.c_norms.push(n,l,h)),"f"==a[0]){var c=a[1].split("/"),u=a[2].split("/"),d=a[3].split("/"),p=parseInt(c[0])-1,_=parseInt(u[0])-1,f=parseInt(d[0])-1,g=parseInt(c[1])-1,m=parseInt(u[1])-1,v=parseInt(d[1])-1,b=parseInt(c[2])-1,P=parseInt(u[2])-1,y=parseInt(d[2])-1,M=t.c_verts.length/3,x=t.c_uvt.length/2,w=t.c_norms.length/3;if(p<0&&(p=M+p+1),_<0&&(_=M+_+1),f<0&&(f=M+f+1),g<0&&(g=x+g+1),m<0&&(m=x+m+1),v<0&&(v=x+v+1),b<0&&(b=w+b+1),P<0&&(P=w+P+1),y<0&&(y=w+y+1),t.i_verts.push(p,_,f),t.i_uvt.push(g,m,v),t.i_norms.push(b,P,y),5==a.length){var E=a[4].split("/"),A=parseInt(E[0])-1,C=parseInt(E[1])-1,S=parseInt(E[2])-1;A<0&&(A=M+A+1),C<0&&(C=x+C+1),S<0&&(S=w+S+1),t.i_verts.push(p,f,A),t.i_uvt.push(g,v,C),t.i_norms.push(b,y,S)}}}return i.to=t.i_verts.length,t},Oa.parse.fromMD2=function(e){e=new Uint8Array(e);var t={},i={};i.ident=Oa.bin.ril(e,0),i.version=Oa.bin.ril(e,4),i.skinwidth=Oa.bin.ril(e,8),i.skinheight=Oa.bin.ril(e,12),i.framesize=Oa.bin.ril(e,16),i.num_skins=Oa.bin.ril(e,20),i.num_vertices=Oa.bin.ril(e,24),i.num_st=Oa.bin.ril(e,28),i.num_tris=Oa.bin.ril(e,32),i.num_glcmds=Oa.bin.ril(e,36),i.num_frames=Oa.bin.ril(e,40),i.offset_skins=Oa.bin.ril(e,44),i.offset_st=Oa.bin.ril(e,48),i.offset_tris=Oa.bin.ril(e,52),i.offset_frames=Oa.bin.ril(e,56),i.offset_glcmds=Oa.bin.ril(e,60),i.offset_end=Oa.bin.ril(e,64);var s=i.offset_st;t.c_uvt=[];for(var r=0;r<i.num_st;r++){var o=Oa.bin.rsl(e,s)/i.skinwidth,a=Oa.bin.rsl(e,s+2)/i.skinheight;t.c_uvt.push(o,a),s+=4}s=i.offset_tris;var n=[],l=[];for(t.i_verts=n,t.i_uvt=l,r=0;r<i.num_tris;r++)n.push(Oa.bin.rsl(e,s),Oa.bin.rsl(e,s+2),Oa.bin.rsl(e,s+4)),l.push(Oa.bin.rsl(e,s+6),Oa.bin.rsl(e,s+8),Oa.bin.rsl(e,s+10)),s+=12;for(s=i.offset_skins,t.skins=[],r=0;r<i.num_skins;r++)t.skins.push(Oa.bin.rASCII0(e,s)),s+=64;s=i.offset_frames,t.frames=[];var h=Oa.parse.fromMD2._normals;for(r=0;r<i.num_frames;r++){var c={},u=Oa.bin.rf(e,s),d=Oa.bin.rf(e,s+4),p=Oa.bin.rf(e,s+8);s+=12;var _=Oa.bin.rf(e,s),f=Oa.bin.rf(e,s+4),g=Oa.bin.rf(e,s+8);s+=12,c.name=Oa.bin.rASCII0(e,s),s+=16,c.verts=[],c.norms=[];for(var m=0;m<i.num_vertices;m++)c.verts.push(e[s]*u+_,e[s+1]*d+f,e[s+2]*p+g),c.norms.push(h[3*e[s+3]],h[3*e[s+3]+1],h[3*e[s+3]+2]),s+=4;t.frames.push(c)}return t},Oa.parse.fromMD2._normals=[-.525731,0,.850651,-.442863,.238856,.864188,-.295242,0,.955423,-.309017,.5,.809017,-.16246,.262866,.951056,0,0,1,0,.850651,.525731,-.147621,.716567,.681718,.147621,.716567,.681718,0,.525731,.850651,.309017,.5,.809017,.525731,0,.850651,.295242,0,.955423,.442863,.238856,.864188,.16246,.262866,.951056,-.681718,.147621,.716567,-.809017,.309017,.5,-.587785,.425325,.688191,-.850651,.525731,0,-.864188,.442863,.238856,-.716567,.681718,.147621,-.688191,.587785,.425325,-.5,.809017,.309017,-.238856,.864188,.442863,-.425325,.688191,.587785,-.716567,.681718,-.147621,-.5,.809017,-.309017,-.525731,.850651,0,0,.850651,-.525731,-.238856,.864188,-.442863,0,.955423,-.295242,-.262866,.951056,-.16246,0,1,0,0,.955423,.295242,-.262866,.951056,.16246,.238856,.864188,.442863,.262866,.951056,.16246,.5,.809017,.309017,.238856,.864188,-.442863,.262866,.951056,-.16246,.5,.809017,-.309017,.850651,.525731,0,.716567,.681718,.147621,.716567,.681718,-.147621,.525731,.850651,0,.425325,.688191,.587785,.864188,.442863,.238856,.688191,.587785,.425325,.809017,.309017,.5,.681718,.147621,.716567,.587785,.425325,.688191,.955423,.295242,0,1,0,0,.951056,.16246,.262866,.850651,-.525731,0,.955423,-.295242,0,.864188,-.442863,.238856,.951056,-.16246,.262866,.809017,-.309017,.5,.681718,-.147621,.716567,.850651,0,.525731,.864188,.442863,-.238856,.809017,.309017,-.5,.951056,.16246,-.262866,.525731,0,-.850651,.681718,.147621,-.716567,.681718,-.147621,-.716567,.850651,0,-.525731,.809017,-.309017,-.5,.864188,-.442863,-.238856,.951056,-.16246,-.262866,.147621,.716567,-.681718,.309017,.5,-.809017,.425325,.688191,-.587785,.442863,.238856,-.864188,.587785,.425325,-.688191,.688191,.587785,-.425325,-.147621,.716567,-.681718,-.309017,.5,-.809017,0,.525731,-.850651,-.525731,0,-.850651,-.442863,.238856,-.864188,-.295242,0,-.955423,-.16246,.262866,-.951056,0,0,-1,.295242,0,-.955423,.16246,.262866,-.951056,-.442863,-.238856,-.864188,-.309017,-.5,-.809017,-.16246,-.262866,-.951056,0,-.850651,-.525731,-.147621,-.716567,-.681718,.147621,-.716567,-.681718,0,-.525731,-.850651,.309017,-.5,-.809017,.442863,-.238856,-.864188,.16246,-.262866,-.951056,.238856,-.864188,-.442863,.5,-.809017,-.309017,.425325,-.688191,-.587785,.716567,-.681718,-.147621,.688191,-.587785,-.425325,.587785,-.425325,-.688191,0,-.955423,-.295242,0,-1,0,.262866,-.951056,-.16246,0,-.850651,.525731,0,-.955423,.295242,.238856,-.864188,.442863,.262866,-.951056,.16246,.5,-.809017,.309017,.716567,-.681718,.147621,.525731,-.850651,0,-.238856,-.864188,-.442863,-.5,-.809017,-.309017,-.262866,-.951056,-.16246,-.850651,-.525731,0,-.716567,-.681718,-.147621,-.716567,-.681718,.147621,-.525731,-.850651,0,-.5,-.809017,.309017,-.238856,-.864188,.442863,-.262866,-.951056,.16246,-.864188,-.442863,.238856,-.809017,-.309017,.5,-.688191,-.587785,.425325,-.681718,-.147621,.716567,-.442863,-.238856,.864188,-.587785,-.425325,.688191,-.309017,-.5,.809017,-.147621,-.716567,.681718,-.425325,-.688191,.587785,-.16246,-.262866,.951056,.442863,-.238856,.864188,.16246,-.262866,.951056,.309017,-.5,.809017,.147621,-.716567,.681718,0,-.525731,.850651,.425325,-.688191,.587785,.587785,-.425325,.688191,.688191,-.587785,.425325,-.955423,.295242,0,-.951056,.16246,.262866,-1,0,0,-.850651,0,.525731,-.955423,-.295242,0,-.951056,-.16246,.262866,-.864188,.442863,-.238856,-.951056,.16246,-.262866,-.809017,.309017,-.5,-.864188,-.442863,-.238856,-.951056,-.16246,-.262866,-.809017,-.309017,-.5,-.681718,.147621,-.716567,-.681718,-.147621,-.716567,-.850651,0,-.525731,-.688191,.587785,-.425325,-.587785,.425325,-.688191,-.425325,.688191,-.587785,-.425325,-.688191,-.587785,-.587785,-.425325,-.688191,-.688191,-.587785,-.425325],Oa.parse.fromCollada=function(e){var t=Oa.parse._buffToStr(e),i=(new DOMParser).parseFromString(t,"text/xml"),s={},r=(i=i.childNodes[0]).getElementsByTagName("asset")[0],o=i.getElementsByTagName("library_geometries")[0],a=i.getElementsByTagName("library_images")[0],n=i.getElementsByTagName("library_materials")[0],l=i.getElementsByTagName("library_effects")[0];return r&&(s.asset=Oa.parse.fromCollada._asset(r)),o&&(s.geometries=Oa.parse.fromCollada._libGeometries(o)),a&&(s.images=Oa.parse.fromCollada._libImages(a)),n&&(s.materials=Oa.parse.fromCollada._libMaterials(n)),l&&(s.effects=Oa.parse.fromCollada._libEffects(l)),s},Oa.parse.fromCollada._asset=function(e){return{created:e.getElementsByTagName("created")[0].textContent,modified:e.getElementsByTagName("modified")[0].textContent,up_axis:e.getElementsByTagName("up_axis")[0].textContent}},Oa.parse.fromCollada._libGeometries=function(e){e=e.getElementsByTagName("geometry");for(var t=[],i=0;i<e.length;i++){var s=e[i],r=Oa.parse.fromCollada._getMesh(s.getElementsByTagName("mesh")[0]);t.push(r)}return t},Oa.parse.fromCollada._getMesh=function(e){for(var t={},i=e.getElementsByTagName("source"),s=t.sources={},r=0;r<i.length;r++){for(var o=i[r].getElementsByTagName("float_array")[0].textContent.split(" "),a=o.length-(""==o[o.length-1]?1:0),n=new Array(a),l=0;l<a;l++)n[l]=parseFloat(o[l]);s[i[r].getAttribute("id")]=n}t.triangles=[];var h=e.getElementsByTagName("triangles");if(null==h)return t;for(r=0;r<h.length;r++){var c={},u=h[r];c.material=u.getAttribute("material");var d=u.getElementsByTagName("input"),p=[];for(l=0;l<d.length;l++){var _=d[l];n=[],p[parseInt(_.getAttribute("offset"))]=n;var f=_.getAttribute("semantic");c["s_"+f]="VERTEX"==f?e.getElementsByTagName("vertices")[0].getElementsByTagName("input")[0].getAttribute("source").substring(1):_.getAttribute("source").substring(1),c["i_"+f]=n,s[c["s_"+f]]}var g=u.getElementsByTagName("p")[0].textContent.split(" "),m=3*Math.floor(g.length/3);for(l=0;l<m;l++)p[l%d.length].push(parseInt(g[l]));t.triangles.push(c)}return t},Oa.parse.fromCollada._libImages=function(e){e=e.getElementsByTagName("image");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("id")]=e[i].getElementsByTagName("init_from")[0].textContent;return t},Oa.parse.fromCollada._libMaterials=function(e){e=e.getElementsByTagName("material");for(var t={},i=0;i<e.length;i++)t[e[i].getAttribute("name")]=e[i].getElementsByTagName("instance_effect")[0].getAttribute("url").substring(1);return t},Oa.parse.fromCollada._libEffects=function(e){e=e.getElementsByTagName("effect");for(var t={},i=0;i<e.length;i++){for(var s={},r=e[i].getElementsByTagName("newparam"),o=0;o<r.length;o++){var a=r[o].getElementsByTagName("surface")[0];a&&(s.surface=a.getElementsByTagName("init_from")[0].textContent)}t[e[i].getAttribute("id")]=s}return t},Oa.parse.from3DS=function(e){e=new Uint8Array(e);var t={};if(19789!=Oa.bin.rsl(e,0))return null;for(var i=Oa.bin.ril(e,2),s=6;s<i;){var r=Oa.bin.rsl(e,s),o=Oa.bin.ril(e,s+2);15677==r&&(t.edit=Oa.parse.from3DS._edit3ds(e,s,o)),45056==r&&(t.keyf=Oa.parse.from3DS._keyf3ds(e,s,o)),s+=o}return t},Oa.parse.from3DS._edit3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=Oa.bin.rsl(e,r),a=Oa.bin.ril(e,r+2);16384==o&&(null==s.objects&&(s.objects=[]),s.objects.push(Oa.parse.from3DS._edit_object(e,r,a))),r+=a}return s},Oa.parse.from3DS._keyf3ds=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=Oa.bin.rsl(e,r),a=Oa.bin.ril(e,r+2);45058==o&&(null==s.desc&&(s.desc=[]),s.desc.push(Oa.parse.from3DS._keyf_objdes(e,r,a))),r+=a}return s},Oa.parse.from3DS._keyf_objdes=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=Oa.bin.rsl(e,r),a=Oa.bin.ril(e,r+2);45072==o&&(s.hierarchy=Oa.parse.from3DS._keyf_objhierarch(e,r,a)),45073==o&&(s.dummy_name=Oa.bin.rASCII0(e,r+6)),r+=a}return s},Oa.parse.from3DS._keyf_objhierarch=function(e,t,i){var s={},r=t+6;return s.name=Oa.bin.rASCII0(e,r),r+=s.name.length+1,s.hierarchy=Oa.bin.rsl(e,r+4),s},Oa.parse.from3DS._edit_object=function(e,t,i){var s={},r=t+6;for(s.name=Oa.bin.rASCII0(e,r),r+=s.name.length+1;r<t+i;){var o=Oa.bin.rsl(e,r),a=Oa.bin.ril(e,r+2);16640==o&&(s.mesh=Oa.parse.from3DS._obj_trimesh(e,r,a)),r+=a}return s},Oa.parse.from3DS._obj_trimesh=function(e,t,i){for(var s={},r=t+6;r<t+i;){var o=Oa.bin.rsl(e,r),a=Oa.bin.ril(e,r+2);16656==o&&(s.vertices=Oa.parse.from3DS._tri_vertexl(e,r,a)),16672==o&&(s.indices=Oa.parse.from3DS._tri_facel1(e,r,a)),16704==o&&(s.uvt=Oa.parse.from3DS._tri_mappingcoors(e,r,a)),16736==o&&(s.local=Oa.parse.from3DS._tri_local(e,r,a)),r+=a}return s},Oa.parse.from3DS._tri_vertexl=function(e,t,i){var s=[],r=t+6,o=Oa.bin.rsl(e,r);r+=2;for(var a=0;a<o;a++)s.push(Oa.bin.rf(e,r)),s.push(Oa.bin.rf(e,r+4)),s.push(Oa.bin.rf(e,r+8)),r+=12;return s},Oa.parse.from3DS._tri_facel1=function(e,t,i){var s=[],r=t+6,o=Oa.bin.rsl(e,r);r+=2;for(var a=0;a<o;a++)s.push(Oa.bin.rsl(e,r)),s.push(Oa.bin.rsl(e,r+2)),s.push(Oa.bin.rsl(e,r+4)),r+=8;return s},Oa.parse.from3DS._tri_mappingcoors=function(e,t,i){var s=[],r=t+6,o=Oa.bin.rsl(e,r);r+=2;for(var a=0;a<o;a++)s.push(Oa.bin.rf(e,r)),s.push(1-Oa.bin.rf(e,r+4)),r+=8;return s},Oa.parse.from3DS._tri_local=function(e,t,i){var s={},r=t+6;return s.X=[Oa.bin.rf(e,r),Oa.bin.rf(e,r+4),Oa.bin.rf(e,r+8)],r+=12,s.Y=[Oa.bin.rf(e,r),Oa.bin.rf(e,r+4),Oa.bin.rf(e,r+8)],r+=12,s.Z=[Oa.bin.rf(e,r),Oa.bin.rf(e,r+4),Oa.bin.rf(e,r+8)],r+=12,s.C=[Oa.bin.rf(e,r),Oa.bin.rf(e,r+4),Oa.bin.rf(e,r+8)],r+=12,s},Oa.parse.fromBIV=function(e){e=new Uint8Array(e);var t={},i={};return i.id=Oa.bin.ril(e,0),i.verS=Oa.bin.ril(e,4),i.texS=Oa.bin.ril(e,8),i.indS=Oa.bin.ril(e,12),i.verO=Oa.bin.ril(e,16),i.verL=Oa.bin.ril(e,20),i.texO=Oa.bin.ril(e,24),i.texL=Oa.bin.ril(e,28),i.indO=Oa.bin.ril(e,32),i.indL=Oa.bin.ril(e,36),0!=i.verO&&(t.vertices=Oa.parse.fromBIV._readFloats(e,i.verO,i.verL)),0!=i.texO&&(t.uvt=Oa.parse.fromBIV._readFloats(e,i.texO,i.texL)),0!=i.indO&&(t.indices=Oa.parse.fromBIV._readInts(e,i.indO,i.indL,i.indS)),t},Oa.parse.toBIV=function(e){for(var t=0,i=0;i<e.indices.length;i++)t=Math.max(t,e.indices[i]);var s=32;t<=65535&&(s=16);var r=40;e.vertices&&(r+=4*e.vertices.length),e.uvt&&(r+=4*e.uvt.length),e.indices&&(r+=e.indices.length*s/8);var o=new Uint8Array(r);Oa.bin.wil(o,0,1769365870),Oa.bin.wil(o,4,32),Oa.bin.wil(o,8,32),Oa.bin.wil(o,12,s);var a=40;return e.vertices&&(Oa.bin.wil(o,16,a),Oa.bin.wil(o,20,4*e.vertices.length),Oa.parse.fromBIV._writeFloats(o,a,e.vertices),a+=4*e.vertices.length),e.uvt&&(Oa.bin.wil(o,24,a),Oa.bin.wil(o,28,4*e.uvt.length),Oa.parse.fromBIV._writeFloats(o,a,e.uvt),a+=4*e.uvt.length),e.indices&&(Oa.bin.wil(o,32,a),Oa.bin.wil(o,36,4*e.indices.length),Oa.parse.fromBIV._writeInts(o,a,e.indices,s)),o.buffer},Oa.parse.fromBIV._readFloats=function(e,t,i){for(var s=[],r=0;r<i/4;r++)s.push(Oa.bin.rf(e,t+4*r));return s},Oa.parse.fromBIV._writeFloats=function(e,t,i){for(var s=0;s<i.length;s++)Oa.bin.wf(e,t+4*s,i[s])},Oa.parse.fromBIV._readInts=function(e,t,i,s){for(var r=[],o=0;o<i/4;o++)16==s&&r.push(Oa.bin.rsl(e,t+2*o)),32==s&&r.push(Oa.bin.ril(e,t+4*o));return r},Oa.parse.fromBIV._writeInts=function(e,t,i,s){for(var r=0;r<i.length;r++)16==s&&Oa.bin.wsl(e,t+2*r,i[r]),32==s&&Oa.bin.wil(e,t+4*r,i[r])},Oa.gen={},Oa.gen.Plane=function(e,t,i,s){i||(i=1),s||(s=1);for(var r={verts:[],inds:[],uvt:[]},o=e+1,a=t+1,n=0;n<a;n++)for(var l=0;l<o;l++){var h=l*(2/e)-1,c=n*(2/t)-1;r.verts.push(h,c,0),r.uvt.push(i*l/e,s*n/t),n<t&&l<e&&r.inds.push(n*o+l,n*o+l+1,(n+1)*o+l,n*o+l+1,(n+1)*o+l,(n+1)*o+l+1)}return r},Oa.gen.Cube=function(){return{verts:[-1,1,-1,1,1,-1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,-1,1,1,-1,1,-1,1,1,-1,1,-1,-1,-1,1,-1,-1,-1,1,1,1,1,1,-1,1,-1,1,1,-1,-1,-1,1,-1,1,1,-1,-1,1,1,1,1,1,-1,-1,-1,1,-1,-1,-1,-1,1,1,-1,1],inds:[0,1,2,1,2,3,4,5,6,5,6,7,8,9,10,9,10,11,12,13,14,13,14,15,16,17,18,17,18,19,20,21,22,21,22,23],uvt:[1/4,1/4,.5,1/4,1/4,.5,.5,.5,1,1/4,3/4,1/4,1,.5,3/4,.5,0,1/4,1/4,1/4,0,.5,1/4,.5,3/4,1/4,.5,1/4,3/4,.5,.5,.5,1/4,1/4,.5,1/4,1/4,0,.5,0,1/4,.5,.5,.5,1/4,3/4,.5,3/4]}},Oa.gen.Sphere=function(e,t){for(var i={verts:[],inds:[],uvt:[]},s=e+1,r=t+1,o=0;o<r;o++)for(var a=0;a<s;a++){var n=-Math.PI/2+o*Math.PI/t,l=2*a*Math.PI/e,h=Math.cos(n)*Math.cos(l),c=Math.sin(n),u=Math.cos(n)*Math.sin(l);i.verts.push(h,c,u),i.uvt.push(a/e,o/t),o<t&&a<e&&i.inds.push(s*o+a,s*o+a+1,s*(o+1)+a,s*o+a+1,s*(o+1)+a,s*(o+1)+a+1)}return i},Oa.mat={},Oa.mat.scale=function(e,t,i){return[e,0,0,0,0,t,0,0,0,0,i,0,0,0,0,1]},Oa.mat.translate=function(e,t,i){return[1,0,0,0,0,1,0,0,0,0,1,0,e,t,i,1]},Oa.mat.rotateDeg=function(e,t,i){var s=Math.PI/180;return Oa.mat.rotate(e*s,t*s,i*s)},Oa.mat.rotate=function(e,t,i){var s=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],r=e,o=t,a=i,n=Math.cos(r),l=Math.cos(o),h=Math.cos(a),c=Math.sin(r),u=Math.sin(o),d=Math.sin(a);return s[0]=l*h,s[1]=-l*d,s[2]=u,s[4]=n*d+c*u*h,s[5]=n*h-c*u*d,s[6]=-c*l,s[8]=c*d-n*u*h,s[9]=c*h+n*u*d,s[10]=n*l,s},Oa.edit={},Oa.edit.interpolate=function(e,t,i,s){for(var r=0;r<e.length;r++)i[r]=e[r]+s*(t[r]-e[r])},Oa.edit.transform=function(e,t){for(var i=0;i<e.length;i+=3){var s=e[i],r=e[i+1],o=e[i+2];e[i+0]=t[0]*s+t[4]*r+t[8]*o+t[12],e[i+1]=t[1]*s+t[5]*r+t[9]*o+t[13],e[i+2]=t[2]*s+t[6]*r+t[10]*o+t[14]}},Oa.edit.unwrap=function(e,t,i){for(var s=new Array(Math.floor(e.length/3)*i),r=0;r<e.length;r++)for(var o=0;o<i;o++)s[r*i+o]=t[e[r]*i+o];return s},Oa.edit.remap=function(e,t,i,s){for(var r=new Array(i.length),o=0;o<e.length;o++)for(var a=0;a<s;a++)r[t[o]*s+a]=i[e[o]*s+a];return r},Oa.utils={},Oa.utils.getAABB=function(e){var t,i,s,r,o,a;r=o=a=-(t=i=s=999999999);for(var n=0;n<e.length;n+=3){var l=e[n+0],h=e[n+1],c=e[n+2];l<t&&(t=l),l>r&&(r=l),h<i&&(i=h),h>o&&(o=h),c<s&&(s=c),h>a&&(a=c)}return{min:{x:t,y:i,z:s},max:{x:r,y:o,z:a}}};u.vec3(),u.vec3();u.vec3();u.vec3([0,-1,0]),u.vec4([0,0,0,1]);const ka=u.vec3();class Va{constructor(e){if(this.objectsVisible=[],this.objectsEdges=[],this.objectsXrayed=[],this.objectsHighlighted=[],this.objectsSelected=[],this.objectsClippable=[],this.objectsPickable=[],this.objectsColorize=[],this.objectsOpacity=[],this.numObjects=0,e){const t=e.metaScene.scene;this.saveObjects(t,e)}}saveObjects(e,t,i){const s=t.rootMetaObject;if(!s)return;const r=s.getObjectIDsInSubtree();this.numObjects=0,this._mask=i?f.apply(i,{}):null;const o=e.objects,a=!i||i.visible,n=!i||i.edges,l=!i||i.xrayed,h=!i||i.highlighted,c=!i||i.selected,u=!i||i.clippable,d=!i||i.pickable,p=!i||i.colorize,_=!i||i.opacity;for(var g=0,m=r.length;g<m;g++){const e=o[r[g]];if(e){if(a&&(this.objectsVisible[g]=e.visible),n&&(this.objectsEdges[g]=e.edges),l&&(this.objectsXrayed[g]=e.xrayed),h&&(this.objectsHighlighted[g]=e.highlighted),c&&(this.objectsSelected[g]=e.selected),u&&(this.objectsClippable[g]=e.clippable),d&&(this.objectsPickable[g]=e.pickable),p){const t=e.colorize;this.objectsColorize[3*g+0]=t[0],this.objectsColorize[3*g+1]=t[1],this.objectsColorize[3*g+2]=t[2]}_&&(this.objectsOpacity[g]=e.opacity),this.numObjects++}}}restoreObjects(e,t){const i=t.rootMetaObject;if(!i)return;const s=i.getObjectIDsInSubtree(),r=this._mask,o=!r||r.visible,a=!r||r.edges,n=!r||r.xrayed,l=!r||r.highlighted,h=!r||r.selected,c=!r||r.clippable,u=!r||r.pickable,d=!r||r.colorize,p=!r||r.opacity,_=e.objects;for(var f=0,g=s.length;f<g;f++){const e=_[s[f]];e&&(o&&(e.visible=this.objectsVisible[f]),a&&(e.edges=this.objectsEdges[f]),n&&(e.xrayed=this.objectsXrayed[f]),l&&(e.highlighted=this.objectsHighlighted[f]),h&&(e.selected=this.objectsSelected[f]),c&&(e.clippable=this.objectsClippable[f]),u&&(e.pickable=this.objectsPickable[f]),d&&(ka[0]=this.objectsColorize[3*f+0],ka[1]=this.objectsColorize[3*f+1],ka[2]=this.objectsColorize[3*f+2],e.colorize=ka),p&&(e.opacity=this.objectsOpacity[f]))}}}const ja=u.vec4(),za=u.vec4(),Ua=u.vec3(),Ga=u.vec3(),Xa=u.vec3(),Ha=u.vec4(),Wa=u.vec4(),Ya=u.vec4();class qa{constructor(e){this._scene=e}dollyToCanvasPos(e,t,i){let s=!1;const r=this._scene.camera;if(e){const t=u.subVec3(e,r.eye,Ua);s=u.lenVec3(t)<i}if("perspective"===r.projection){r.ortho.scale=r.ortho.scale-i;const s=this._unproject(t,Ha),o=u.subVec3(s,r.eye,Ya),a=u.mulVec3Scalar(u.normalizeVec3(o),-i,[]);if(r.eye=[r.eye[0]-a[0],r.eye[1]-a[1],r.eye[2]-a[2]],r.look=[r.look[0]-a[0],r.look[1]-a[1],r.look[2]-a[2]],e){const t=u.subVec3(e,r.eye,Ua),i=u.lenVec3(t),s=u.mulVec3Scalar(u.normalizeVec3(u.subVec3(r.look,r.eye,Ga)),i);r.look=[r.eye[0]+s[0],r.eye[1]+s[1],r.eye[2]+s[2]]}}else if("ortho"===r.projection){const e=this._unproject(t,Ha);r.ortho.scale=r.ortho.scale-i,r.ortho._update();const s=this._unproject(t,Wa),o=u.subVec3(s,e,Ya),a=u.mulVec3Scalar(u.normalizeVec3(u.subVec3(r.look,r.eye,Ua)),-i,Ga),n=u.addVec3(o,a,Xa);r.eye=[r.eye[0]-n[0],r.eye[1]-n[1],r.eye[2]-n[2]],r.look=[r.look[0]-n[0],r.look[1]-n[1],r.look[2]-n[2]]}return s}_unproject(e,t){const i=this._scene.camera,s=i.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),a=[0,0,-1,1],n=u.dotVec4(a,r)/u.dotVec4(a,o);return i.project.unproject(e,n,ja,za,t),t}destroy(){}}const Ka=u.vec3(),Za=u.vec3(),Qa=u.vec3(),$a=u.vec4(),Ja=u.vec4(),en=u.vec4();class tn{constructor(e,t){this._scene=e,this._configs=t,this._pivotWorldPos=u.vec3(),this._cameraOffset=u.vec3(),this._azimuth=0,this._polar=0,this._radius=0,this._pivotPosSet=!1,this._pivoting=!1,this._shown=!1,this._pivotViewPos=u.vec4(),this._pivotProjPos=u.vec4(),this._pivotCanvasPos=u.vec2(),this._cameraDirty=!0,this._onViewMatrix=this._scene.camera.on("viewMatrix",(()=>{this._cameraDirty=!0})),this._onProjMatrix=this._scene.camera.on("projMatrix",(()=>{this._cameraDirty=!0})),this._onTick=this._scene.on("tick",(()=>{this.updatePivotElement()}))}updatePivotElement(){const e=this._scene.camera,t=this._scene.canvas;if(this._pivoting&&this._cameraDirty){u.transformPoint3(e.viewMatrix,this.getPivotPos(),this._pivotViewPos),this._pivotViewPos[3]=1,u.transformPoint4(e.projMatrix,this._pivotViewPos,this._pivotProjPos);const i=t.boundary,s=i[2],r=i[3];this._pivotCanvasPos[0]=Math.floor((1+this._pivotProjPos[0]/this._pivotProjPos[3])*s/2),this._pivotCanvasPos[1]=Math.floor((1-this._pivotProjPos[1]/this._pivotProjPos[3])*r/2);const o=t.canvas.getBoundingClientRect();this._pivotElement&&(this._pivotElement.style.left=Math.floor(o.left+this._pivotCanvasPos[0])-this._pivotElement.clientWidth/2+window.scrollX+"px",this._pivotElement.style.top=Math.floor(o.top+this._pivotCanvasPos[1])-this._pivotElement.clientHeight/2+window.scrollY+"px"),this._cameraDirty=!1}}setPivotElement(e){this._pivotElement=e}startPivot(){if(this._cameraLookingDownwards())return this._pivoting=!1,!1;const e=this._scene.camera;let t=u.lookAtMat4v(e.eye,e.look,e.worldUp);u.transformPoint3(t,this.getPivotPos(),this._cameraOffset);const i=this.getPivotPos();this._cameraOffset[2]+=u.distVec3(e.eye,i),t=u.inverseMat4(t);const s=u.transformVec3(t,this._cameraOffset),r=u.vec3();if(u.subVec3(e.eye,i,r),u.addVec3(r,s),e.zUp){const e=r[1];r[1]=r[2],r[2]=e}this._radius=u.lenVec3(r),this._polar=Math.acos(r[1]/this._radius),this._azimuth=Math.atan2(r[0],r[2]),this._pivoting=!0}_cameraLookingDownwards(){const e=this._scene.camera,t=u.normalizeVec3(u.subVec3(e.look,e.eye,Ka)),i=u.cross3Vec3(t,e.worldUp,Za);return u.sqLenVec3(i)<=1e-4}getPivoting(){return this._pivoting}setPivotPos(e){this._pivotWorldPos.set(e),this._pivotPosSet=!0}setCanvasPivotPos(e){const t=this._scene.camera,i=Math.abs(u.distVec3(this._scene.center,t.eye)),s=t.project.transposedMatrix,r=s.subarray(8,12),o=s.subarray(12),a=[0,0,-1,1],n=u.dotVec4(a,r)/u.dotVec4(a,o),l=$a;t.project.unproject(e,n,Ja,en,l);const h=u.normalizeVec3(u.subVec3(l,t.eye,Ka)),c=u.addVec3(t.eye,u.mulVec3Scalar(h,i,Za),Qa);this.setPivotPos(c)}getPivotPos(){return this._pivotPosSet?this._pivotWorldPos:this._scene.camera.look}continuePivot(e,t){if(!this._pivoting)return;if(0===e&&0===t)return;const i=this._scene.camera;var s=-e;const r=-t;1===i.worldUp[2]&&(s=-s),this._azimuth+=.01*-s,this._polar+=.01*r,this._polar=u.clamp(this._polar,.001,Math.PI-.001);const o=[this._radius*Math.sin(this._polar)*Math.sin(this._azimuth),this._radius*Math.cos(this._polar),this._radius*Math.sin(this._polar)*Math.cos(this._azimuth)];if(1===i.worldUp[2]){const e=o[1];o[1]=o[2],o[2]=e}const a=u.lenVec3(u.subVec3(i.look,i.eye,u.vec3())),n=this.getPivotPos();u.addVec3(o,n);let l=u.lookAtMat4v(o,n,i.worldUp);l=u.inverseMat4(l);const h=u.transformVec3(l,this._cameraOffset);l[12]-=h[0],l[13]-=h[1],l[14]-=h[2];const c=[l[8],l[9],l[10]];i.eye=[l[12],l[13],l[14]],u.subVec3(i.eye,u.mulVec3Scalar(c,a),i.look),i.up=[l[4],l[5],l[6]],this.showPivot()}showPivot(){this._shown||(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this.updatePivotElement(),this._pivotElement.style.visibility="visible",this._shown=!0,this._hideTimeout=window.setTimeout((()=>{this.hidePivot()}),1e3)))}hidePivot(){this._shown&&(null!==this._hideTimeout&&(window.clearTimeout(this._hideTimeout),this._hideTimeout=null),this._pivotElement&&(this._pivotElement.style.visibility="hidden"),this._shown=!1)}endPivot(){this._pivoting=!1}destroy(){this._scene.camera.off(this._onViewMatrix),this._scene.camera.off(this._onProjMatrix),this._scene.off(this._onTick)}}class sn{constructor(e,t){this._scene=e.scene,this._cameraControl=e,this._scene.canvas.canvas.oncontextmenu=function(e){e.preventDefault()},this._configs=t,this.schedulePickEntity=!1,this.schedulePickSurface=!1,this.pickCursorPos=u.vec2(),this.picked=!1,this.pickedSurface=!1,this.pickResult=null,this._lastPickedEntityId=null,this._needFireEvents=!1}update(){if(!this._configs.pointerEnabled)return;if(!this.schedulePickEntity&&!this.schedulePickSurface)return;this.picked=!1,this.pickedSurface=!1,this._needFireEvents=!1;const e=this._cameraControl.hasSubs("hoverSurface");if(this.schedulePickSurface&&this.pickResult&&this.pickResult.worldPos){const t=this.pickResult.canvasPos;if(t[0]===this.pickCursorPos[0]&&t[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!0,this._needFireEvents=e,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}if(this.schedulePickEntity&&this.pickResult){const e=this.pickResult.canvasPos;if(e[0]===this.pickCursorPos[0]&&e[1]===this.pickCursorPos[1])return this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!1,this.schedulePickEntity=!1,void(this.schedulePickSurface=!1)}this.schedulePickSurface?(this.pickResult=this._scene.pick({pickSurface:!0,pickSurfaceNormal:!1,canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!0,this._needFireEvents=!0)):(this.pickResult=this._scene.pick({canvasPos:this.pickCursorPos}),this.pickResult&&(this.picked=!0,this.pickedSurface=!1,this._needFireEvents=!0)),this.schedulePickEntity=!1,this.schedulePickSurface=!1}fireEvents(){if(this._needFireEvents){if(this.picked&&this.pickResult&&this.pickResult.entity){const e=this.pickResult.entity.id;this._lastPickedEntityId!==e&&(void 0!==this._lastPickedEntityId&&this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._cameraControl.fire("hoverEnter",this.pickResult,!0),this._lastPickedEntityId=e),this._cameraControl.fire("hover",this.pickResult,!0),this.pickResult.worldPos&&(this.pickedSurface=!0,this._cameraControl.fire("hoverSurface",this.pickResult,!0))}else void 0!==this._lastPickedEntityId&&(this._cameraControl.fire("hoverOut",{entity:this._scene.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),this._cameraControl.fire("hoverOff",{canvasPos:this.pickCursorPos},!0);this.pickResult=null,this._needFireEvents=!1}}destroy(){}}const rn=u.vec2();class on{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;let a,n,l,h=0,c=0,d=0,p=0,_=!1;const f=u.vec3();let g=!0;const m=this._scene.canvas.canvas,v=[];function b(e=!0){m.style.cursor="move",h=s.pointerCanvasPos[0],c=s.pointerCanvasPos[1],d=s.pointerCanvasPos[0],p=s.pointerCanvasPos[1],e&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(_=!0,f.set(o.pickResult.worldPos)):_=!1)}document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!0}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;const s=t.keyCode;v[s]=!1}),m.addEventListener("mousedown",this._mouseDownHandler=t=>{if(i.active&&i.pointerEnabled)switch(t.which){case 1:v[e.input.KEY_SHIFT]||i.planView?(a=!0,b()):(a=!0,b(!1));break;case 2:n=!0,b();break;case 3:l=!0,i.panRightClick&&b()}}),document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{if(!i.active||!i.pointerEnabled)return;if(!a&&!n&&!l)return;const t=e.canvas.boundary,o=t[2]-t[0],d=t[3]-t[1],p=s.pointerCanvasPos[0],g=s.pointerCanvasPos[1];if(v[e.input.KEY_SHIFT]||i.planView||!i.panRightClick&&n||i.panRightClick&&l){const t=p-h,i=g-c,s=e.camera;if("perspective"===s.projection){const o=Math.abs(_?u.lenVec3(u.subVec3(f,e.camera.eye,[])):e.camera.eyeLookDist)*Math.tan(s.perspective.fov/2*Math.PI/180);r.panDeltaX+=1.5*t*o/d,r.panDeltaY+=1.5*i*o/d}else r.panDeltaX+=.5*s.ortho.scale*(t/d),r.panDeltaY+=.5*s.ortho.scale*(i/d)}else!a||n||l||i.planView||(i.firstPerson?(r.rotateDeltaY-=(p-h)/o*i.dragRotationRate/2,r.rotateDeltaX+=(g-c)/d*(i.dragRotationRate/4)):(r.rotateDeltaY-=(p-h)/o*(1.5*i.dragRotationRate),r.rotateDeltaX+=(g-c)/d*(1.5*i.dragRotationRate)));h=p,c=g}),m.addEventListener("mousemove",this._canvasMouseMoveHandler=e=>{i.active&&i.pointerEnabled&&s.mouseover&&(g=!0)}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{if(i.active&&i.pointerEnabled)switch(e.which){case 1:case 2:case 3:a=!1,n=!1,l=!1}}),m.addEventListener("mouseup",this._mouseUpHandler=e=>{if(i.active&&i.pointerEnabled){switch(e.which){case 3:!function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y}(e,rn);const i=rn[0],s=rn[1];Math.abs(i-d)<3&&Math.abs(s-p)<3&&t.cameraControl.fire("rightClick",{canvasPos:rn,event:e},!0)}m.style.removeProperty("cursor")}}),m.addEventListener("mouseenter",this._mouseEnterHandler=()=>{i.active&&i.pointerEnabled});const P=1/60;let y=null;m.addEventListener("wheel",this._mouseWheelHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=performance.now()/1e3;var o=null!==y?t-y:0;y=t,o>.05&&(o=.05),o<P&&(o=P);const a=Math.max(-1,Math.min(1,40*-e.deltaY));if(0===a)return;const n=a/Math.abs(a);r.dollyDelta+=-n*o*i.mouseWheelDollyRate,g&&(s.followPointerDirty=!0,g=!1),e.preventDefault()})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler),e.removeEventListener("mousedown",this._mouseDownHandler),document.removeEventListener("mousemove",this._documentMouseMoveHandler),e.removeEventListener("mousemove",this._canvasMouseMoveHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._mouseUpHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("wheel",this._mouseWheelHandler)}}const an=u.vec3(),nn=u.vec3(),ln=u.vec3(),hn=u.vec3(),cn=u.vec3(),un={eye:u.vec3(),look:u.vec3(),up:u.vec3()};class dn{constructor(e,t,i,s,r){this._scene=e;const o=t.cameraControl,a=e.camera;e.input.on("keydown",this._documentKeyDownHandler=r=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const n=o._isKeyDownForAction(o.AXIS_VIEW_RIGHT),l=o._isKeyDownForAction(o.AXIS_VIEW_BACK),h=o._isKeyDownForAction(o.AXIS_VIEW_LEFT),c=o._isKeyDownForAction(o.AXIS_VIEW_FRONT),d=o._isKeyDownForAction(o.AXIS_VIEW_TOP),p=o._isKeyDownForAction(o.AXIS_VIEW_BOTTOM);if(!(n||l||h||c||d||p))return;const _=e.aabb,f=u.getAABB3Diag(_);u.getAABB3Center(_,an);const g=Math.abs(f/Math.tan(t.cameraFlight.fitFOV*u.DEGTORAD)),m=1.1*f;un.orthoScale=m,n?(un.eye.set(u.addVec3(an,u.mulVec3Scalar(a.worldRight,g,nn),cn)),un.look.set(an),un.up.set(a.worldUp)):l?(un.eye.set(u.addVec3(an,u.mulVec3Scalar(a.worldForward,g,nn),cn)),un.look.set(an),un.up.set(a.worldUp)):h?(un.eye.set(u.addVec3(an,u.mulVec3Scalar(a.worldRight,-g,nn),cn)),un.look.set(an),un.up.set(a.worldUp)):c?(un.eye.set(u.addVec3(an,u.mulVec3Scalar(a.worldForward,-g,nn),cn)),un.look.set(an),un.up.set(a.worldUp)):d?(un.eye.set(u.addVec3(an,u.mulVec3Scalar(a.worldUp,g,nn),cn)),un.look.set(an),un.up.set(u.normalizeVec3(u.mulVec3Scalar(a.worldForward,1,ln),hn))):p&&(un.eye.set(u.addVec3(an,u.mulVec3Scalar(a.worldUp,-g,nn),cn)),un.look.set(an),un.up.set(u.normalizeVec3(u.mulVec3Scalar(a.worldForward,-1,ln)))),!i.firstPerson&&i.followPointer&&t.pivotController.setPivotPos(an),t.cameraFlight.duration>0?t.cameraFlight.flyTo(un,(()=>{t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot()})):(t.cameraFlight.jumpTo(un),t.pivotController.getPivoting()&&i.followPointer&&t.pivotController.showPivot())})}reset(){}destroy(){document.removeEventListener("keydown",this._documentKeyDownHandler)}}class pn{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,a=t.pivotController,n=t.cameraControl;this._clicks=0,this._timeout=null,this._lastPickedEntityId=null;let l=!1,h=!1;const c=this._scene.canvas.canvas,d=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i&&i.entity?i.entity.aabb:e.aabb;if(s){const i=e.camera;u.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};c.addEventListener("mousemove",this._canvasMouseMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(l||h)return;const r=n.hasSubs("hover"),a=n.hasSubs("hoverOut"),c=n.hasSubs("hoverOff"),u=n.hasSubs("hoverSurface");if(r||a||c||u)if(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=u,o.update(),o.pickResult){const t=o.pickResult.entity.id;this._lastPickedEntityId!==t&&(void 0!==this._lastPickedEntityId&&n.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),n.fire("hoverEnter",o.pickResult,!0),this._lastPickedEntityId=t),n.fire("hover",o.pickResult,!0),o.pickResult.worldPos&&n.fire("hoverSurface",o.pickResult,!0)}else void 0!==this._lastPickedEntityId&&(n.fire("hoverOut",{entity:e.objects[this._lastPickedEntityId]},!0),this._lastPickedEntityId=void 0),n.fire("hoverOff",{canvasPos:o.pickCursorPos},!0)}),c.addEventListener("mousedown",this._canvasMouseDownHandler=t=>{if(1===t.which&&(l=!0),3===t.which&&(h=!0),1===t.which&&i.active&&i.pointerEnabled&&(s.mouseDownClientX=t.clientX,s.mouseDownClientY=t.clientY,s.mouseDownCursorX=s.pointerCanvasPos[0],s.mouseDownCursorY=s.pointerCanvasPos[1],!i.firstPerson&&i.followPointer&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickSurface=!0,o.update(),1===t.which))){const t=o.pickResult;t&&t.worldPos?(a.setPivotPos(t.worldPos),a.startPivot()):(i.smartPivot?a.setCanvasPivotPos(s.pointerCanvasPos):a.setPivotPos(e.camera.look),a.startPivot())}}),document.addEventListener("mouseup",this._documentMouseUpHandler=e=>{1===e.which&&(l=!1),3===e.which&&(h=!1)}),c.addEventListener("mouseup",this._canvasMouseUpHandler=r=>{if(!i.active||!i.pointerEnabled)return;if(1!==r.which)return;if(a.hidePivot(),Math.abs(r.clientX-s.mouseDownClientX)>3||Math.abs(r.clientY-s.mouseDownClientY)>3)return;const l=n.hasSubs("picked"),h=n.hasSubs("pickedNothing"),c=n.hasSubs("pickedSurface"),p=n.hasSubs("doublePicked"),_=n.hasSubs("doublePickedSurface"),f=n.hasSubs("doublePickedNothing");if(!(i.doublePickFlyTo||p||_||f))return(l||h||c)&&(o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=!0,o.schedulePickSurface=c,o.update(),o.pickResult?(n.fire("picked",o.pickResult,!0),o.pickedSurface&&n.fire("pickedSurface",o.pickResult,!0)):n.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0)),void(this._clicks=0);if(this._clicks++,1===this._clicks)this._timeout=setTimeout((()=>{o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo,o.schedulePickSurface=c,o.update(),o.pickResult?(n.fire("picked",o.pickResult,!0),o.pickedSurface&&(n.fire("pickedSurface",o.pickResult,!0),!i.firstPerson&&i.followPointer&&(t.pivotController.setPivotPos(o.pickResult.worldPos),t.pivotController.startPivot()&&t.pivotController.showPivot()))):n.fire("pickedNothing",{canvasPos:s.pointerCanvasPos},!0),this._clicks=0}),250);else{if(null!==this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null),o.pickCursorPos=s.pointerCanvasPos,o.schedulePickEntity=i.doublePickFlyTo||p||_,o.schedulePickSurface=o.schedulePickEntity&&_,o.update(),o.pickResult){if(n.fire("doublePicked",o.pickResult,!0),o.pickedSurface&&n.fire("doublePickedSurface",o.pickResult,!0),i.doublePickFlyTo&&(d(o.pickResult),!i.firstPerson&&i.followPointer)){const e=o.pickResult.entity.aabb,i=u.getAABB3Center(e);t.pivotController.setPivotPos(i),t.pivotController.startPivot()&&t.pivotController.showPivot()}}else if(n.fire("doublePickedNothing",{canvasPos:s.pointerCanvasPos},!0),i.doublePickFlyTo&&(d(),!i.firstPerson&&i.followPointer)){const i=e.aabb,s=u.getAABB3Center(i);t.pivotController.setPivotPos(s),t.pivotController.startPivot()&&t.pivotController.showPivot()}this._clicks=0}},!1)}reset(){this._clicks=0,this._lastPickedEntityId=null,this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("mousemove",this._canvasMouseMoveHandler),e.removeEventListener("mousedown",this._canvasMouseDownHandler),document.removeEventListener("mouseup",this._documentMouseUpHandler),e.removeEventListener("mouseup",this._canvasMouseUpHandler),this._timeout&&(window.clearTimeout(this._timeout),this._timeout=null)}}class _n{constructor(e,t,i,s,r){this._scene=e;const o=e.input,a=[],n=e.canvas.canvas;t.pickController;let l=!0;document.addEventListener("mousemove",this._documentMouseMoveHandler=()=>{l=!0}),document.addEventListener("keydown",this._documentKeyDownHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;a[r]=!0,r===o.KEY_SHIFT&&(n.style.cursor="move")}),document.addEventListener("keyup",this._documentKeyUpHandler=t=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const r=t.keyCode;a[r]=!1,r===o.KEY_SHIFT&&(n.style.cursor=null)}),this._onTick=e.on("tick",(n=>{if(!i.active||!i.pointerEnabled||!e.input.keyboardEnabled)return;if(!s.mouseover)return;const h=t.cameraControl,c=n.deltaTime/1e3;if(!i.planView){const e=h._isKeyDownForAction(h.ROTATE_Y_POS,a),s=h._isKeyDownForAction(h.ROTATE_Y_NEG,a),o=h._isKeyDownForAction(h.ROTATE_X_POS,a),n=h._isKeyDownForAction(h.ROTATE_X_NEG,a),l=c*i.keyboardRotationRate;(e||s||o||n)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),e?r.rotateDeltaY+=l:s&&(r.rotateDeltaY-=l),o?r.rotateDeltaX+=l:n&&(r.rotateDeltaX-=l),!i.firstPerson&&i.followPointer&&t.pivotController.startPivot())}if(!a[o.KEY_CTRL]&&!a[o.KEY_ALT]){const e=h._isKeyDownForAction(h.DOLLY_BACKWARDS,a),o=h._isKeyDownForAction(h.DOLLY_FORWARDS,a);if(e||o){const a=c*i.keyboardDollyRate;!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),o?r.dollyDelta-=a:e&&(r.dollyDelta+=a),l&&(s.followPointerDirty=!0,l=!1)}}const u=h._isKeyDownForAction(h.PAN_FORWARDS,a),d=h._isKeyDownForAction(h.PAN_BACKWARDS,a),p=h._isKeyDownForAction(h.PAN_LEFT,a),_=h._isKeyDownForAction(h.PAN_RIGHT,a),f=h._isKeyDownForAction(h.PAN_UP,a),g=h._isKeyDownForAction(h.PAN_DOWN,a),m=(a[o.KEY_ALT]?.3:1)*c*i.keyboardPanRate;(u||d||p||_||f||g)&&(!i.firstPerson&&i.followPointer&&t.pivotController.startPivot(),g?r.panDeltaY+=m:f&&(r.panDeltaY+=-m),_?r.panDeltaX+=-m:p&&(r.panDeltaX+=m),d?r.panDeltaZ+=m:u&&(r.panDeltaZ+=-m))}))}reset(){}destroy(){this._scene.off(this._onTick),document.removeEventListener("mousemove",this._documentMouseMoveHandler),document.removeEventListener("keydown",this._documentKeyDownHandler),document.removeEventListener("keyup",this._documentKeyUpHandler)}}const fn=u.vec3();class gn{constructor(e,t,i,s,r){this._scene=e;const o=e.camera,a=t.pickController,n=t.pivotController,l=t.panController;let h=1,c=1,d=null;this._onTick=e.on("tick",(()=>{if(!i.active||!i.pointerEnabled)return;let t="default";if(Math.abs(r.dollyDelta)<.001&&(r.dollyDelta=0),Math.abs(r.rotateDeltaX)<.001&&(r.rotateDeltaX=0),Math.abs(r.rotateDeltaY)<.001&&(r.rotateDeltaY=0),0===r.rotateDeltaX&&0===r.rotateDeltaY||(r.dollyDelta=0),i.followPointer&&--h<=0&&(h=1,0!==r.dollyDelta)){if(0===r.rotateDeltaY&&0===r.rotateDeltaX&&i.followPointer&&s.followPointerDirty&&(a.pickCursorPos=s.pointerCanvasPos,a.schedulePickSurface=!0,a.update(),a.pickResult&&a.pickResult.worldPos?d=a.pickResult.worldPos:(c=1,d=null),s.followPointerDirty=!1),d){const t=Math.abs(u.lenVec3(u.subVec3(d,e.camera.eye,fn)));c=t/i.dollyProximityThreshold}c<i.dollyMinSpeed&&(c=i.dollyMinSpeed)}const p=r.dollyDelta*c;if(0===r.rotateDeltaY&&0===r.rotateDeltaX||(!i.firstPerson&&i.followPointer&&n.getPivoting()?(n.continuePivot(r.rotateDeltaY,r.rotateDeltaX),n.showPivot()):(0!==r.rotateDeltaX&&(i.firstPerson?o.pitch(-r.rotateDeltaX):o.orbitPitch(r.rotateDeltaX)),0!==r.rotateDeltaY&&(i.firstPerson?o.yaw(r.rotateDeltaY):o.orbitYaw(r.rotateDeltaY))),r.rotateDeltaX*=i.rotationInertia,r.rotateDeltaY*=i.rotationInertia,t="grabbing"),Math.abs(r.panDeltaX)<.001&&(r.panDeltaX=0),Math.abs(r.panDeltaY)<.001&&(r.panDeltaY=0),Math.abs(r.panDeltaZ)<.001&&(r.panDeltaZ=0),0!==r.panDeltaX||0!==r.panDeltaY||0!==r.panDeltaZ){const e=u.vec3();let s,a;if(e[0]=r.panDeltaX,e[1]=r.panDeltaY,e[2]=r.panDeltaZ,i.constrainVertical){o.xUp?(s=o.eye[0],a=o.look[0]):o.yUp?(s=o.eye[1],a=o.look[1]):o.zUp&&(s=o.eye[2],a=o.look[2]),o.pan(e);const t=o.eye,i=o.look;o.xUp?(t[0]=s,i[0]=a):o.yUp?(t[1]=s,i[1]=a):o.zUp&&(t[2]=s,i[2]=a),o.eye=t,o.look=i}else o.pan(e);t="grabbing"}if(r.panDeltaX*=i.panInertia,r.panDeltaY*=i.panInertia,r.panDeltaZ*=i.panInertia,0!==p){if(t=p<0?"zoom-in":"zoom-out",i.firstPerson){let e,t;if(i.constrainVertical&&(o.xUp?(e=o.eye[0],t=o.look[0]):o.yUp?(e=o.eye[1],t=o.look[1]):o.zUp&&(e=o.eye[2],t=o.look[2])),i.followPointer?l.dollyToCanvasPos(d,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0):(o.pan([0,0,p]),o.ortho.scale=o.ortho.scale-p),i.constrainVertical){const i=o.eye,s=o.look;o.xUp?(i[0]=e,s[0]=t):o.yUp?(i[1]=e,s[1]=t):o.zUp&&(i[2]=e,s[2]=t),o.eye=i,o.look=s}}else i.planView,i.followPointer?l.dollyToCanvasPos(d,s.pointerCanvasPos,-p)&&(s.followPointerDirty=!0):(o.ortho.scale=o.ortho.scale+p,o.zoom(p));r.dollyDelta*=i.dollyInertia}a.fireEvents(),document.body.style.cursor=t}))}destroy(){this._scene.off(this._onTick)}}class mn{constructor(e,t,i,s,r){this._scene=e;const o=this._scene.canvas.canvas;o.addEventListener("mouseenter",this._mouseEnterHandler=()=>{s.mouseover=!0}),o.addEventListener("mouseleave",this._mouseLeaveHandler=()=>{s.mouseover=!1,o.style.cursor=null}),document.addEventListener("mousemove",this._mouseMoveHandler=e=>{vn(e,o,s.pointerCanvasPos)}),o.addEventListener("mousedown",this._mouseDownHandler=e=>{i.active&&i.pointerEnabled&&(vn(e,o,s.pointerCanvasPos),s.mouseover=!0)}),o.addEventListener("mouseup",this._mouseUpHandler=e=>{i.active&&i.pointerEnabled})}reset(){}destroy(){const e=this._scene.canvas.canvas;document.removeEventListener("mousemove",this._mouseMoveHandler),e.removeEventListener("mouseenter",this._mouseEnterHandler),e.removeEventListener("mouseleave",this._mouseLeaveHandler),e.removeEventListener("mousedown",this._mouseDownHandler),e.removeEventListener("mouseup",this._mouseUpHandler)}}function vn(e,t,i){if(e){const{x:s,y:r}=t.getBoundingClientRect();i[0]=e.clientX-s,i[1]=e.clientY-r}else e=window.event,i[0]=e.x,i[1]=e.y;return i}const bn=function(e,t){if(e){let i=e.target,s=0,r=0;for(;i.offsetParent;)s+=i.offsetLeft,r+=i.offsetTop,i=i.offsetParent;t[0]=e.pageX-s,t[1]=e.pageY-r}else e=window.event,t[0]=e.x,t[1]=e.y;return t};class Pn{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController,a=t.pivotController,n=u.vec2(),l=u.vec2(),h=u.vec2(),c=u.vec2(),d=[],p=this._scene.canvas.canvas;let _=0,f=!1;this._onTick=e.on("tick",(()=>{f=!1})),p.addEventListener("touchstart",this._canvasTouchStartHandler=t=>{if(!i.active||!i.pointerEnabled)return;t.stopPropagation(),t.preventDefault();const r=t.touches,l=t.changedTouches;for(s.touchStartTime=Date.now(),1===r.length&&1===l.length&&(s.touchStartTime,bn(r[0],n),i.followPointer&&(o.pickCursorPos=n,o.schedulePickSurface=!0,o.update(),i.planView||(o.picked&&o.pickedSurface&&o.pickResult&&o.pickResult.worldPos?(a.setPivotPos(o.pickResult.worldPos),!i.firstPerson&&a.startPivot()&&a.showPivot()):(i.smartPivot?a.setCanvasPivotPos(s.pointerCanvasPos):a.setPivotPos(e.camera.look),!i.firstPerson&&a.startPivot()&&a.showPivot()))));d.length<r.length;)d.push(u.vec2());for(let e=0,t=r.length;e<t;++e)bn(r[e],d[e]);_=r.length}),p.addEventListener("touchmove",this._canvasTouchMoveHandler=t=>{if(!i.active||!i.pointerEnabled)return;if(t.stopPropagation(),t.preventDefault(),f)return;f=!0;const a=e.canvas.boundary,n=a[2]-a[0],p=a[3]-a[1],g=t.touches;if(t.touches.length===_){if(1===_){bn(g[0],l),u.subVec2(l,d[0],c);const t=c[0],s=c[1];if(i.planView){const o=e.camera;if("perspective"===o.projection){const a=Math.abs(e.camera.eyeLookDist)*Math.tan(o.perspective.fov/2*Math.PI/180);r.panDeltaX+=t*a/p*i.touchPanRate,r.panDeltaY+=s*a/p*i.touchPanRate}else r.panDeltaX+=.5*o.ortho.scale*(t/p)*i.touchPanRate,r.panDeltaY+=.5*o.ortho.scale*(s/p)*i.touchPanRate}else r.rotateDeltaY-=t/n*(1*i.dragRotationRate),r.rotateDeltaX+=s/p*(1.5*i.dragRotationRate)}else if(2===_){const t=g[0],a=g[1];bn(t,l),bn(a,h);const n=u.geometricMeanVec2(d[0],d[1]),c=u.geometricMeanVec2(l,h),_=u.vec2();u.subVec2(n,c,_);const f=_[0],m=_[1],v=e.camera,b=u.distVec2([t.pageX,t.pageY],[a.pageX,a.pageY]),P=(u.distVec2(d[0],d[1])-b)*i.touchDollyRate;if(r.dollyDelta=P,Math.abs(P)<1)if("perspective"===v.projection){const t=o.pickResult?o.pickResult.worldPos:e.center,s=Math.abs(u.lenVec3(u.subVec3(t,e.camera.eye,[])))*Math.tan(v.perspective.fov/2*Math.PI/180);r.panDeltaX-=f*s/p*i.touchPanRate,r.panDeltaY-=m*s/p*i.touchPanRate}else r.panDeltaX-=.5*v.ortho.scale*(f/p)*i.touchPanRate,r.panDeltaY-=.5*v.ortho.scale*(m/p)*i.touchPanRate;s.pointerCanvasPos=c}for(let e=0;e<_;++e)bn(g[e],d[e])}})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchmove",this._canvasTouchMoveHandler),this._scene.off(this._onTick)}}class yn{constructor(e,t,i,s,r){this._scene=e;const o=t.pickController;t.pivotController;const a=t.cameraControl;let n;const l=[],h=new Float32Array(2);let c=-1,d=-1;const p=this._scene.canvas.canvas,_=i=>{let s;i&&i.worldPos&&(s=i.worldPos);const r=i?i.entity.aabb:e.aabb;if(s){const i=e.camera;u.subVec3(i.eye,i.look,[]),t.cameraFlight.flyTo({aabb:r})}else t.cameraFlight.flyTo({aabb:r})};p.addEventListener("touchstart",this._canvasTouchStartHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=e.touches,s=e.changedTouches;for(n=Date.now(),1===t.length&&1===s.length?(c=n,h[0]=t[0].pageX,h[1]=t[0].pageY):c=-1;l.length<t.length;)l.push(new Float32Array(2));for(let e=0,i=t.length;e<i;++e)l[e][0]=t[e].pageX,l[e][1]=t[e].pageY;l.length=t.length,e.stopPropagation()},{passive:!0}),p.addEventListener("touchend",this._canvasTouchEndHandler=e=>{if(!i.active||!i.pointerEnabled)return;const t=Date.now(),s=e.touches,r=e.changedTouches;a.hasSubs("picked"),a.hasSubs("pickedNothing");const n=a.hasSubs("pickedSurface");a.hasSubs("doublePicked"),a.hasSubs("doublePickedSurface"),a.hasSubs("doublePickedNothing"),0===s.length&&1===r.length&&c>-1&&t-c<150&&(d>-1&&c-d<325?(o.pickCursorPos[0]=Math.round(r[0].clientX),o.pickCursorPos[1]=Math.round(r[0].clientY),o.schedulePickEntity=!0,o.schedulePickSurface=n,o.update(),o.pickResult?(a.fire("doublePicked",o.pickResult),o.pickedSurface&&a.fire("doublePickedSurface",o.pickResult),i.doublePickFlyTo&&_(o.pickResult)):(a.fire("doublePickedNothing"),i.doublePickFlyTo&&_()),d=-1):u.distVec2(l[0],h)<4&&(o.pickCursorPos[0]=Math.round(r[0].clientX),o.pickCursorPos[1]=Math.round(r[0].clientY),o.schedulePickEntity=!0,o.schedulePickSurface=n,o.update(),o.pickResult?(a.fire("picked",o.pickResult),o.pickedSurface&&a.fire("pickedSurface",o.pickResult)):a.fire("pickedNothing"),d=t),c=-1),l.length=s.length;for(let e=0,t=s.length;e<t;++e)l[e][0]=s[e].pageX,l[e][1]=s[e].pageY;e.stopPropagation()},{passive:!0})}reset(){}destroy(){const e=this._scene.canvas.canvas;e.removeEventListener("touchstart",this._canvasTouchStartHandler),e.removeEventListener("touchend",this._canvasTouchEndHandler)}}class Mn extends A{constructor(e,t={}){super(e,t),this.PAN_LEFT=0,this.PAN_RIGHT=1,this.PAN_UP=2,this.PAN_DOWN=3,this.PAN_FORWARDS=4,this.PAN_BACKWARDS=5,this.ROTATE_X_POS=6,this.ROTATE_X_NEG=7,this.ROTATE_Y_POS=8,this.ROTATE_Y_NEG=9,this.DOLLY_FORWARDS=10,this.DOLLY_BACKWARDS=11,this.AXIS_VIEW_RIGHT=12,this.AXIS_VIEW_BACK=13,this.AXIS_VIEW_LEFT=14,this.AXIS_VIEW_FRONT=15,this.AXIS_VIEW_TOP=16,this.AXIS_VIEW_BOTTOM=17,this._keyMap={},this.scene.canvas.canvas.oncontextmenu=e=>{e.preventDefault()},this._configs={tapInterval:150,doubleTapInterval:325,tapDistanceThreshold:4,active:!0,keyboardLayout:"qwerty",navMode:"orbit",planView:!1,firstPerson:!1,followPointer:!0,doublePickFlyTo:!0,panRightClick:!0,showPivot:!1,pointerEnabled:!0,constrainVertical:!1,smartPivot:!1,dragRotationRate:360,keyboardRotationRate:90,rotationInertia:0,keyboardPanRate:1,touchPanRate:1,panInertia:.5,keyboardDollyRate:10,mouseWheelDollyRate:100,touchDollyRate:.2,dollyInertia:0,dollyProximityThreshold:30,dollyMinSpeed:.04},this._states={pointerCanvasPos:u.vec2(),mouseover:!1,followPointerDirty:!0,mouseDownClientX:0,mouseDownClientY:0,mouseDownCursorX:0,mouseDownCursorY:0,touchStartTime:null,activeTouches:[],tapStartPos:u.vec2(),tapStartTime:-1,lastTapTime:-1},this._updates={rotateDeltaX:0,rotateDeltaY:0,panDeltaX:0,panDeltaY:0,panDeltaZ:0,dollyDelta:0};const i=this.scene;this._controllers={cameraControl:this,pickController:new sn(this,this._configs),pivotController:new tn(i,this._configs),panController:new qa(i),cameraFlight:new Ia(this,{duration:.5})},this._handlers=[new mn(this.scene,this._controllers,this._configs,this._states,this._updates),new Pn(this.scene,this._controllers,this._configs,this._states,this._updates),new on(this.scene,this._controllers,this._configs,this._states,this._updates),new dn(this.scene,this._controllers,this._configs,this._states,this._updates),new pn(this.scene,this._controllers,this._configs,this._states,this._updates),new yn(this.scene,this._controllers,this._configs,this._states,this._updates),new _n(this.scene,this._controllers,this._configs,this._states,this._updates)],this._cameraUpdater=new gn(this.scene,this._controllers,this._configs,this._states,this._updates),this.navMode=t.navMode,t.planView&&(this.planView=t.planView),this.constrainVertical=t.constrainVertical,t.keyboardLayout?this.keyboardLayout=t.keyboardLayout:this.keyMap=t.keyMap,this.doublePickFlyTo=t.doublePickFlyTo,this.panRightClick=t.panRightClick,this.active=t.active,this.followPointer=t.followPointer,this.rotationInertia=t.rotationInertia,this.keyboardPanRate=t.keyboardPanRate,this.touchPanRate=t.touchPanRate,this.keyboardRotationRate=t.keyboardRotationRate,this.dragRotationRate=t.dragRotationRate,this.touchDollyRate=t.touchDollyRate,this.dollyInertia=t.dollyInertia,this.dollyProximityThreshold=t.dollyProximityThreshold,this.dollyMinSpeed=t.dollyMinSpeed,this.panInertia=t.panInertia,this.pointerEnabled=!0,this.keyboardDollyRate=t.keyboardDollyRate,this.mouseWheelDollyRate=t.mouseWheelDollyRate}set keyMap(e){if(e=e||"qwerty",f.isString(e)){const t=this.scene.input,i={};switch(e){default:this.error("Unsupported value for 'keyMap': "+e+" defaulting to 'qwerty'");case"qwerty":i[this.PAN_LEFT]=[t.KEY_A],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_Z],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_W,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_Q,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6];break;case"azerty":i[this.PAN_LEFT]=[t.KEY_Q],i[this.PAN_RIGHT]=[t.KEY_D],i[this.PAN_UP]=[t.KEY_W],i[this.PAN_DOWN]=[t.KEY_X],i[this.PAN_BACKWARDS]=[],i[this.PAN_FORWARDS]=[],i[this.DOLLY_FORWARDS]=[t.KEY_Z,t.KEY_ADD],i[this.DOLLY_BACKWARDS]=[t.KEY_S,t.KEY_SUBTRACT],i[this.ROTATE_X_POS]=[t.KEY_DOWN_ARROW],i[this.ROTATE_X_NEG]=[t.KEY_UP_ARROW],i[this.ROTATE_Y_POS]=[t.KEY_A,t.KEY_LEFT_ARROW],i[this.ROTATE_Y_NEG]=[t.KEY_E,t.KEY_RIGHT_ARROW],i[this.AXIS_VIEW_RIGHT]=[t.KEY_NUM_1],i[this.AXIS_VIEW_BACK]=[t.KEY_NUM_2],i[this.AXIS_VIEW_LEFT]=[t.KEY_NUM_3],i[this.AXIS_VIEW_FRONT]=[t.KEY_NUM_4],i[this.AXIS_VIEW_TOP]=[t.KEY_NUM_5],i[this.AXIS_VIEW_BOTTOM]=[t.KEY_NUM_6]}this._keyMap=i}else{const t=e;this._keyMap=t}}get keyMap(){return this._keyMap}_isKeyDownForAction(e,t){const i=this._keyMap[e];if(!i)return!1;t||(t=this.scene.input.keyDown);for(let e=0,s=i.length;e<s;e++)if(t[i[e]])return!0;return!1}set pivotElement(e){this._controllers.pivotController.setPivotElement(e)}set active(e){this._configs.active=!1!==e}get active(){return this._configs.active}set navMode(e){"firstPerson"!==(e=e||"orbit")&&"orbit"!==e&&"planView"!==e&&(this.error("Unsupported value for navMode: "+e+" - supported values are 'orbit', 'firstPerson' and 'planView' - defaulting to 'orbit'"),e="orbit"),this._configs.firstPerson="firstPerson"===e,this._configs.planView="planView"===e,(this._configs.firstPerson||this._configs.planView)&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this._configs.navMode=e}get navMode(){return this._configs.navMode}set pointerEnabled(e){this._reset(),this._configs.pointerEnabled=!!e}_reset(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.reset&&t.reset()}this._updates.panDeltaX=0,this._updates.panDeltaY=0,this._updates.rotateDeltaX=0,this._updates.rotateDeltaY=0,this._updates.dolyDelta=0}get pointerEnabled(){return this._configs.pointerEnabled}set followPointer(e){this._configs.followPointer=!1!==e}get followPointer(){return this._configs.followPointer}set pivotPos(e){this._controllers.pivotController.setPivotPos(e)}get pivotPos(){return this._controllers.pivotController.getPivotPos()}set dollyToPointer(e){this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer=e}get dollyToPointer(){return this.warn("dollyToPointer property is deprecated - replaced with followPointer"),this.followPointer}set panToPointer(e){this.warn("panToPointer property is deprecated - replaced with followPointer")}get panToPointer(){return this.warn("panToPointer property is deprecated - replaced with followPointer"),!1}set planView(e){this._configs.planView=!!e,this._configs.firstPerson=!1,this._configs.planView&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot()),this.warn("planView property is deprecated - replaced with navMode")}get planView(){return this.warn("planView property is deprecated - replaced with navMode"),this._configs.planView}set firstPerson(e){this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson=!!e,this._configs.planView=!1,this._configs.firstPerson&&(this._controllers.pivotController.hidePivot(),this._controllers.pivotController.endPivot())}get firstPerson(){return this.warn("firstPerson property is deprecated - replaced with navMode"),this._configs.firstPerson}set constrainVertical(e){this._configs.constrainVertical=!!e}get constrainVertical(){return this._configs.constrainVertical}set doublePickFlyTo(e){this._configs.doublePickFlyTo=!1!==e}get doublePickFlyTo(){return this._configs.doublePickFlyTo}set panRightClick(e){this._configs.panRightClick=!1!==e}get panRightClick(){return this._configs.panRightClick}set rotationInertia(e){this._configs.rotationInertia=null!=e?e:0}get rotationInertia(){return this._configs.rotationInertia}set keyboardPanRate(e){this._configs.keyboardPanRate=null!=e?e:5}set touchPanRate(e){this._configs.touchPanRate=null!=e?e:1}get touchPanRate(){return this._configs.touchPanRate}get keyboardPanRate(){return this._configs.keyboardPanRate}set keyboardRotationRate(e){this._configs.keyboardRotationRate=null!=e?e:90}get keyboardRotationRate(){return this._configs.keyboardRotationRate}set dragRotationRate(e){this._configs.dragRotationRate=null!=e?e:360}get dragRotationRate(){return this._configs.dragRotationRate}set keyboardDollyRate(e){this._configs.keyboardDollyRate=null!=e?e:15}get keyboardDollyRate(){return this._configs.keyboardDollyRate}set touchDollyRate(e){this._configs.touchDollyRate=null!=e?e:.2}get touchDollyRate(){return this._configs.touchDollyRate}set mouseWheelDollyRate(e){this._configs.mouseWheelDollyRate=null!=e?e:100}get mouseWheelDollyRate(){return this._configs.mouseWheelDollyRate}set dollyInertia(e){this._configs.dollyInertia=null!=e?e:0}get dollyInertia(){return this._configs.dollyInertia}set dollyProximityThreshold(e){this._configs.dollyProximityThreshold=null!=e?e:35}get dollyProximityThreshold(){return this._configs.dollyProximityThreshold}set dollyMinSpeed(e){this._configs.dollyMinSpeed=null!=e?e:.04}get dollyMinSpeed(){return this._configs.dollyMinSpeed}set panInertia(e){this._configs.panInertia=null!=e?e:.5}get panInertia(){return this._configs.panInertia}set keyboardLayout(e){"qwerty"!==(e=e||"qwerty")&&"azerty"!==e&&(this.error("Unsupported value for keyboardLayout - defaulting to 'qwerty'"),e="qwerty"),this._configs.keyboardLayout=e,this.keyMap=this._configs.keyboardLayout}get keyboardLayout(){return this._configs.keyboardLayout}set smartPivot(e){this._configs.smartPivot=!1!==e}get smartPivot(){return this._configs.smartPivot}destroy(){this._destroyHandlers(),this._destroyControllers(),this._cameraUpdater.destroy(),super.destroy()}_destroyHandlers(){for(let e=0,t=this._handlers.length;e<t;e++){const t=this._handlers[e];t.destroy&&t.destroy()}}_destroyControllers(){for(let e=0,t=this._controllers.length;e<t;e++){const t=this._controllers[e];t.destroy&&t.destroy()}}}class xn{constructor(e,t,i,s,r,o,a,n,l){this.id=t,this.projectId=i,this.revisionId=s,this.author=r,this.createdAt=o,this.creatingApplication=a,this.schema=n,this.metaScene=e,this.rootMetaObject=l}getJSON(){var e=[];return function t(i){var s={id:i.id,extId:i.extId,type:i.type,name:i.name};i.parent&&(s.parent=i.parent.id),e.push(s);var r=i.children;if(r)for(var o=0,a=r.length;o<a;o++)t(r[o])}(this.rootMetaObject),{id:this.id,projectId:this.projectId,revisionId:this.revisionId,metaObjects:e}}}class wn{constructor(e,t,i,s,r,o,a,n,l){this.metaModel=e,this.id=t,this.originalSystemId=i,this.name=s,this.type=r,o&&(this.properties=o),null!=a&&(this.parent=a),null!=n&&(this.children=n),null!=l&&(this.external=l)}getObjectIDsInSubtree(){const e=[];return function t(i){if(!i)return;e.push(i.id);const s=i.children;if(s)for(var r=0,o=s.length;r<o;r++)t(s[r])}(this),e}withMetaObjectsInSubtree(e){!function t(i){if(!i)return;e(i);const s=i.children;if(s)for(var r=0,o=s.length;r<o;r++)t(s[r])}(this)}getObjectIDsInSubtreeByType(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=e[i];const r=[];return function e(i){if(!i)return;t[i.type]&&r.push(i.id);const s=i.children;if(s)for(var o=0,a=s.length;o<a;o++)e(s[o])}(this),r}getJSON(){var e={id:this.id,type:this.type,name:this.name};return this.parent&&(e.parent=this.parent.id),e}}class En{constructor(e,t){this.viewer=e,this.scene=t,this.metaModels={},this.metaObjects={},this.metaObjectsByType={},this._typeCounts={},this._eventSubs={}}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}off(e){}createMetaModel(e,t,i={}){const s=t.projectId||"none",r=t.revisionId||"none",o=t.metaObjects,a=t.author,n=t.createdAt,l=t.creatingApplication,h=t.schema,c=new xn(this,e,s,r,a,n,l,h,null);this.metaModels[e]=c;for(let t=0,s=o.length;t<s;t++){const s=o[t],r=s.type,a=i.globalizeObjectIds?u.globalizeObjectId(e,s.id):s.id,n=s.id,l=s.name,h=s.properties,d=null,p=null,_=s.external,f=new wn(c,a,n,l,r,h,d,p,_);this.metaObjects[a]=f,(this.metaObjectsByType[r]||(this.metaObjectsByType[r]={}))[a]=f,void 0===this._typeCounts[r]?this._typeCounts[r]=1:this._typeCounts[r]++}for(let t=0,s=o.length;t<s;t++){const s=o[t],r=i.globalizeObjectIds?u.globalizeObjectId(e,s.id):s.id,a=this.metaObjects[r];if(a)if(void 0===s.parent||null===s.parent)c.rootMetaObject=a;else if(s.parent){const t=i.globalizeObjectIds?u.globalizeObjectId(e,s.parent):s.parent;let r=this.metaObjects[t];r&&(a.parent=r,r.children=r.children||[],r.children.push(a))}}return this.fire("metaModelCreated",e),c}destroyMetaModel(e){const t=this.metaModels[e];t&&(this._removeMetaModel(t),this.fire("metaModelDestroyed",e))}_removeMetaModel(e){const t=this.metaObjects,i=this.metaObjectsByType;let s=e=>{delete t[e.id];const r=i[e.type];r&&r[e.id]&&(delete r[e.id],0==--this._typeCounts[e.type]&&(delete this._typeCounts[e.type],delete i[e.type]));const o=e.children;if(o)for(let e=0,t=o.length;e<t;e++){const t=o[e];s(t)}};s(e.rootMetaObject),delete this.metaModels[e.id]}getObjectIDsByType(e){const t=this.metaObjectsByType[e];return t?Object.keys(t):[]}getObjectIDsInSubtree(e,t,i){const s=[],r=this.metaObjects[e],o=t&&t.length>0?An(t):null,a=i&&i.length>0?An(i):null;return function e(t){if(!t)return;var i=!0;(a&&a[t.type]||o&&!o[t.type])&&(i=!1),i&&s.push(t.id);const r=t.children;if(r)for(var n=0,l=r.length;n<l;n++)e(r[n])}(r),s}withMetaObjectsInSubtree(e,t){const i=this.metaObjects[e];i&&i.withMetaObjectsInSubtree(t)}}function An(e){const t={};for(var i=0,s=e.length;i<s;i++)t[e[i]]=!0;return t}class Cn{constructor(e){this.language="en",this.scene=new pt(this,{canvasId:e.canvasId,canvasElement:e.canvasElement,webgl2:!1,contextAttr:{preserveDrawingBuffer:!1!==e.preserveDrawingBuffer,premultipliedAlpha:!!e.premultipliedAlpha,antialias:!1!==e.antialias},spinnerElementId:e.spinnerElementId,transparent:!1!==e.transparent,gammaInput:!0,gammaOutput:!1,backgroundColor:e.backgroundColor,backgroundColorFromAmbientLight:e.backgroundColorFromAmbientLight,ticksPerRender:1,ticksPerOcclusionTest:20,units:e.units,scale:e.scale,origin:e.origin,saoEnabled:e.saoEnabled,alphaDepthMask:!1!==e.alphaDepthMask,entityOffsetsEnabled:!!e.entityOffsetsEnabled,logarithmicDepthBufferEnabled:!!e.logarithmicDepthBufferEnabled,pbrEnabled:!!e.pbrEnabled}),this.metaScene=new En(this,this.scene),this.id=e.id||this.scene.id,this.camera=this.scene.camera,this.cameraFlight=new Ia(this.scene,{duration:.5}),this.cameraControl=new Mn(this.scene,{doublePickFlyTo:!0}),this._plugins=[],this._eventSubs={}}on(e,t){let i=this._eventSubs[e];i||(i=[],this._eventSubs[e]=i),i.push(t)}fire(e,t){const i=this._eventSubs[e];if(i)for(let e=0,s=i.length;e<s;e++)i[e](t)}off(e){}log(e){console.log(`[xeokit viewer ${this.id}]: ${e}`)}error(e){console.error(`[xeokit viewer ${this.id}]: ${e}`)}addPlugin(e){this._plugins.push(e)}removePlugin(e){for(let t=0,i=this._plugins.length;t<i;t++){const i=this._plugins[t];if(i===e)return i.clear&&i.clear(),void this._plugins.splice(t,1)}}sendToPlugins(e,t){for(let i=0,s=this._plugins.length;i<s;i++){const s=this._plugins[i];s.send&&s.send(e,t)}}clear(){throw'Viewer#clear() no longer implemented - use \'#sendToPlugins("clear") instead'}resetView(){throw"Viewer#resetView() no longer implemented - use CameraMemento & ObjectsMemento classes instead"}beginSnapshot(){this._snapshotBegun||(this.scene._renderer.beginSnapshot(),this._snapshotBegun=!0)}getSnapshot(e={}){const t=!this._snapshotBegun;this._snapshotBegun||this.beginSnapshot(),e.includeGizmos||this.sendToPlugins("snapshotStarting");const i=void 0!==e.width&&void 0!==e.height,s=this.scene.canvas.canvas,r=s.clientWidth,o=s.clientHeight,a=s.style.width,n=s.style.height,l=e.width?Math.floor(e.width):s.width,h=e.height?Math.floor(e.height):s.height;i&&(s.style.width=l+"px",s.style.height=h+"px"),this.scene._renderer.renderSnapshot();const c=this.scene._renderer.readSnapshot(e);return i&&(s.style.width=a,s.style.height=n,s.width=r,s.height=o,this.scene.glRedraw()),e.includeGizmos||this.sendToPlugins("snapshotFinished"),t&&this.endSnapshot(),c}endSnapshot(){this._snapshotBegun&&(this.scene._renderer.endSnapshot(),this.scene._renderer.render({force:!0}),this._snapshotBegun=!1)}destroy(){const e=this._plugins.slice();for(let t=0,i=e.length;t<i;t++)e[t].destroy();this.scene.destroy()}}class Sn{constructor(e={}){this._dataDir=e.dataDir||""}getProjects(e,t){const i=this._dataDir+"/projects/index.json";f.loadJSON(i,e,t)}getProject(e,t,i){const s=this._dataDir+"/projects/"+e+"/index.json";f.loadJSON(s,t,i)}getMetadata(e,t,i,s){const r=this._dataDir+"/projects/"+e+"/models/"+t+"/metadata.json";f.loadJSON(r,i,s)}getGeometry(e,t,i,s){const r=this._dataDir+"/projects/"+e+"/models/"+t+"/geometry.xkt";f.loadArraybuffer(r,i,s)}getObjectInfo(e,t,i,s,r){const o=this._dataDir+"/projects/"+e+"/models/"+t+"/objects/"+i+"/properties.json";f.loadJSON(o,s,r)}getIssues(e,t,i,s){const r=this._dataDir+"/projects/"+e+"/models/"+t+"/issues.json";f.loadJSON(r,i,s)}}class Dn{constructor(e,t){this.items=e||[],this._lastUniqueId=(t||0)+1}addItem(){let e;if(2===arguments.length){const t=arguments[0];if(e=arguments[1],this.items[t])throw"ID clash: '"+t+"'";return this.items[t]=e,t}for(e=arguments[0]||{};;){const t=this._lastUniqueId++;if(!this.items[t])return this.items[t]=e,t}}removeItem(e){const t=this.items[e];return delete this.items[e],t}}class Ln{constructor(e,t,i,s){this.bimViewer=e?e.bimViewer||e:this,this.server=e?e.server:i,this.viewer=e?e.viewer:s,this._children=[],e&&e._children.push(this),this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0,this._enabled=null,this._active=null}fire(e,t,i){this._events||(this._events={}),this._eventSubs||(this._eventSubs={}),!0!==i&&(this._events[e]=t||!0);const s=this._eventSubs[e];let r;if(s)for(const i in s)s.hasOwnProperty(i)&&(r=s[i],this._eventCallDepth++,this._eventCallDepth<300?r.callback.call(r.scope,t):this.error("fire: potential stack overflow from recursive event '"+e+"' - dropping this event"),this._eventCallDepth--)}on(e,t,i){this._events||(this._events={}),this._subIdMap||(this._subIdMap=new Dn),this._subIdEvents||(this._subIdEvents={}),this._eventSubs||(this._eventSubs={});let s=this._eventSubs[e];s||(s={},this._eventSubs[e]=s);const r=this._subIdMap.addItem();s[r]={callback:t,scope:i||this},this._subIdEvents[r]=e;const o=this._events[e];return void 0!==o&&t.call(i||this,o),r}off(e){if(null==e)return;if(!this._subIdEvents)return;const t=this._subIdEvents[e];if(t){delete this._subIdEvents[e];const i=this._eventSubs[t];i&&delete i[e],this._subIdMap.removeItem(e)}}once(e,t,i){const s=this,r=this.on(e,(function(e){s.off(r),t.call(i||this,e)}),i)}log(e){e="[LOG] "+e,window.console.log(e)}warn(e){e="[WARN] "+e,window.console.warn(e)}error(e){e="[ERROR] "+e,window.console.error(e)}_mutexActivation(e){const t=e.length;for(let i=0;i<t;i++){e[i].on("active",function(){const s=i;return function(i){if(i)for(let i=0;i<t;i++)i!==s&&e[i].setActive(!1)}}())}}setEnabled(e){this._enabled!==e&&(this._enabled=e,this.fire("enabled",this._enabled))}getEnabled(){return this._enabled}setActive(e){this._active!==e&&(this._active=e,this.fire("active",this._active))}getActive(){return this._active}destroy(){if(!this.destroyed){this.fire("destroyed",this.destroyed=!0),this._subIdMap=null,this._subIdEvents=null,this._eventSubs=null,this._events=null,this._eventCallDepth=0;for(let e=0,t=this._children.length;e<t;e++)this._children.destroy();this._children=[]}}}class Bn extends Ln{constructor(e,t={}){super(e,t);const i=t.busyModalBackdropElement||document.body;if(!i)throw"Missing config: busyModalBackdropElement";this._modal=document.createElement("div"),this._modal.classList.add("xeokit-busy-modal"),this._modal.innerHTML='<div class="xeokit-busy-modal-content"><div class="xeokit-busy-modal-body"><div class="xeokit-busy-modal-message">Default text</div></div></div>',i.appendChild(this._modal),this._modalVisible=!1,this._modal.style.display="hidden"}show(e){this._modalVisible=!0,this._modal.querySelector(".xeokit-busy-modal-message").innerText=e,this._modal.style.display="block"}hide(){this._modalVisible=!1,this._modal.style.display="none"}destroy(){super.destroy(),this._modal&&(this._modal.parentNode.removeChild(this._modal),this._modal=null)}}const Tn=u.vec3();class Rn extends Ln{constructor(e,t={}){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement,s=this.viewer.camera;this._modelMementos={},s.eye=[.577,.577,.577],s.look=[0,0,0],s.up=[-1,1,-1],this.bimViewer._modelsExplorer.on("modelLoaded",(e=>{this._saveModelMemento(e)})),this.bimViewer._modelsExplorer.on("modelUnloaded",(e=>{this._destroyModelMemento(e)})),this.on("enabled",(e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")})),this.on("active",(e=>{e?i.classList.add("active"):i.classList.remove("active")})),i.addEventListener("click",(e=>{this.getEnabled()&&this.reset(),e.preventDefault()}))}_saveModelMemento(e){const t=this.viewer.metaScene.metaModels[e];if(!t)return;const i=new Va;i.saveObjects(this.viewer.scene,t,{visible:!0,edges:!0,xrayed:!0,highlighted:!0,selected:!0,clippable:!0,pickable:!0,colorize:!1,opacity:!1}),this._modelMementos[e]=i}_restoreModelMemento(e){const t=this.viewer.metaScene.metaModels[e];if(!t)return;this._modelMementos[e].restoreObjects(this.viewer.scene,t)}_destroyModelMemento(e){delete this._modelMementos[e]}reset(){const e=this.viewer.scene.modelIds;for(var t=0,i=e.length;t<i;t++){const i=e[t];this._restoreModelMemento(i)}this.bimViewer.unShowObjectInExplorers(),this.fire("reset",!0),this._resetCamera()}_resetCamera(){const e=this.viewer,t=e.scene,i=t.getAABB(t.visibleObjectIds),s=u.getAABB3Diag(i),r=u.getAABB3Center(i,Tn),o=Math.abs(s/Math.tan(32.5)),a=t.camera,n=a.yUp?[-1,-1,-1]:[1,1,1],l=a.yUp?[-1,1,-1]:[-1,1,1];e.cameraControl.pivotPos=r,e.cameraControl.planView=!1,e.cameraFlight.flyTo({look:r,eye:[r[0]-o*n[0],r[1]-o*n[1],r[2]-o*n[2]],up:l,orthoScale:1.3*s,projection:"perspective",duration:1})}}const Fn=u.vec3();class Nn extends Ln{constructor(e,t={}){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",(e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")})),this.on("active",(e=>{e?i.classList.add("active"):i.classList.remove("active")})),i.addEventListener("click",(e=>{this.getEnabled()&&this.fit(),e.preventDefault()}))}fit(){const e=this.viewer.scene,t=e.getAABB(e.visibleObjectIds);this.viewer.cameraFlight.flyTo({aabb:t}),this.viewer.cameraControl.pivotPos=u.getAABB3Center(t,Fn)}set fov(e){this.viewer.scene.cameraFlight.fitFOV=e}get fov(){return this.viewer.scene.cameraFlight.fitFOV}set duration(e){this.viewer.scene.cameraFlight.duration=e}get duration(){return this.viewer.scene.cameraFlight.duration}}class In extends Ln{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement,s=this.viewer.cameraControl,r=t.cameraControlNavModeMediator;s.navMode="orbit",s.followPointer=!0,this.on("enabled",(e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")})),this.on("active",(e=>{e?i.classList.add("active"):i.classList.remove("active")})),this.on("active",(e=>{r.setFirstPersonModeActive(e),e?(s.followPointer=!0,s.pivoting=!1):s.pivoting=!0})),i.addEventListener("click",(e=>{if(this.getEnabled()){const e=this.getActive();this.setActive(!e)}e.preventDefault()})),this.bimViewer.on("reset",(()=>{this.setActive(!1)}))}}class On extends Ln{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",(e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")})),this.on("active",(e=>{e?(i.classList.add("active"),this.viewer.cameraControl.doublePickFlyTo=!1,this._onPick=this.viewer.cameraControl.on("picked",(e=>{e.entity&&(e.entity.visible=!1)}))):(i.classList.remove("active"),this.viewer.cameraControl.doublePickFlyTo=!1,void 0!==this._onPick&&(this.viewer.cameraControl.off(this._onPick),this._onPick=void 0))})),i.addEventListener("click",(e=>{if(this.getEnabled()){this.bimViewer._sectionTool.hideControl();const e=this.getActive();this.setActive(!e)}e.preventDefault()})),this.bimViewer.on("reset",(()=>{this.setActive(!1)}))}}class kn extends Ln{constructor(e,t){if(super(e),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",(e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")})),this.on("active",(e=>{e?(i.classList.add("active"),this._onPick=this.viewer.cameraControl.on("picked",(e=>{e.entity&&(e.entity.selected=!e.entity.selected)}))):(i.classList.remove("active"),void 0!==this._onPick&&(this.viewer.cameraControl.off(this._onPick),this._onPick=void 0))})),i.addEventListener("click",(e=>{if(this.getEnabled()){this.bimViewer._sectionTool.hideControl();const e=this.getActive();this.setActive(!e)}e.preventDefault()})),this.bimViewer.on("reset",(()=>{this.setActive(!1)}))}}class Vn extends Ln{constructor(e,t){if(super(e),!t.buttonElement)throw"Missing config: buttonElement";const i=t.buttonElement;this.on("enabled",(e=>{e?i.classList.remove("disabled"):i.classList.add("disabled")})),this.on("active",(e=>{e?(i.classList.add("active"),this._onPick=this.viewer.cameraControl.on("picked",(e=>{if(!e.entity)return;const t=e.entity,i=t.model;if(!i)return;const s=this.bimViewer.getLoadedProjectId();if(!s)return void this.error("Query tool: should be a project loaded - ignoring query-pick");const r=i.id,o=t.id,a=this.viewer.metaScene.metaObjects[o];if(!a)return;const n={projectId:s,modelId:r,objectId:o,objectName:a.name,objectType:a.type};this.fire("queryPicked",n)})),this._onPickedNothing=this.viewer.cameraControl.on("pickedNothing",(e=>{this.fire("queryNotPicked",!1)}))):(i.classList.remove("active"),void 0!==this._onPick&&(this.viewer.cameraControl.off(this._onPick),this.viewer.cameraControl.off(this._onPickedNothing),this._onPick=void 0,this._onPickedNothing=void 0))})),i.addEventListener("click",(e=>{if(this.bimViewer._sectionTool.hideControl(),this.getEnabled()){const e=this.getActive();this.setActive(!e)}e.preventDefault()})),this.bimViewer.on("reset",(()=>{this.setActive(!1)}))}}const jn=u.AABB3(),zn=u.vec3();class Un extends o{constructor(e={}){if(!e.sectionPlanesPlugin)throw"Missing config: sectionPlanesPlugin";super(f.apply({},e)),this._sectionPlanesPlugin=e.sectionPlanesPlugin,this._viewer=this._sectionPlanesPlugin.viewer,this._onSceneSectionPlaneCreated=this._viewer.scene.on("sectionPlaneCreated",(()=>{this._buildMenu()})),this._onSceneSectionPlaneDestroyed=this._viewer.scene.on("sectionPlaneDestroyed",(()=>{this._buildMenu()})),this._buildMenu()}_buildMenu(){const e=this._sectionPlanesPlugin,t=Object.values(e.sectionPlanes),i=[];for(let s=0,r=t.length;s<r;s++){const r=t[s];i.push({getTitle:()=>"Slice #"+(s+1),doHoverEnter(t){e.hideControl(),e.showControl(r.id)},doHoverLeave(t){e.hideControl()},items:[[{getTitle:e=>"Edit",doAction:t=>{e.hideControl(),e.showControl(r.id);const i=r.pos;jn.set(this._viewer.scene.aabb),u.getAABB3Center(jn,zn),jn[0]+=i[0]-zn[0],jn[1]+=i[1]-zn[1],jn[2]+=i[2]-zn[2],jn[3]+=i[0]-zn[0],jn[4]+=i[1]-zn[1],jn[5]+=i[2]-zn[2],this._viewer.cameraFlight.flyTo({aabb:jn,fitFOV:65})}},{getTitle:e=>"Flip",doAction:e=>{r.flipDir()}},{getTitle:e=>"Delete",doAction:e=>{r.destroy()}}]]})}this.items=[[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}},{title:"Flip Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.flipSections()}}],i]}destroy(){super.destroy();const e=this._viewer.scene;e.off(this._onSceneSectionPlaneCreated),e.off(this._onSceneSectionPlaneDestroyed)}}class Gn extends Ln{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";if(!t.menuButtonElement)throw"Missing config: menuButtonElement";this._buttonElement=t.buttonElement,this._counterElement=t.counterElement,this._menuButtonElement=t.menuButtonElement,this._menuButtonArrowElement=t.menuButtonArrowElement,this._sectionPlanesPlugin=new Zo(this.viewer,{}),this._sectionToolContextMenu=new Un({sectionPlanesPlugin:this._sectionPlanesPlugin,hideOnMouseDown:!1}),this._sectionPlanesPlugin.setOverviewVisible(!1),this.on("enabled",(e=>{e?(this._buttonElement.classList.remove("disabled"),this._counterElement&&this._counterElement.classList.remove("disabled"),this._menuButtonElement.classList.remove("disabled"),this._menuButtonArrowElement.classList.remove("disabled")):(this._buttonElement.classList.add("disabled"),this._counterElement&&this._counterElement.classList.add("disabled"),this._menuButtonElement.classList.add("disabled"),this._menuButtonArrowElement.classList.add("disabled"))})),this.on("active",(e=>{e?(this._buttonElement.classList.add("active"),this._counterElement&&this._counterElement.classList.add("active"),this._menuButtonElement.classList.add("active"),this._menuButtonArrowElement.classList.add("active")):(this._buttonElement.classList.remove("active"),this._counterElement&&this._counterElement.classList.remove("active"),this._menuButtonElement.classList.remove("active"),this._menuButtonArrowElement.classList.remove("active"))})),this.on("active",(e=>{e||this._sectionPlanesPlugin.hideControl()})),this._buttonElement.addEventListener("click",(e=>{if(!this.getEnabled())return;if(e.target===this._menuButtonElement||e.target.parentNode===this._menuButtonElement)return;const t=this.getActive();this.setActive(!t),e.preventDefault()})),document.addEventListener("mousedown",(e=>{if(!e.target.classList.contains("xeokit-context-menu-item"))if(e.target===this._menuButtonElement||e.target.parentNode===this._menuButtonElement)if(e.preventDefault(),this._sectionToolContextMenu.shown)this._sectionToolContextMenu.hide();else{this._sectionToolContextMenu.context={bimViewer:this.bimViewer,viewer:this.viewer,sectionTool:this};const e=this._menuButtonElement.getBoundingClientRect();this._sectionToolContextMenu.show(e.left,e.bottom+5)}else this._sectionToolContextMenu.hide()})),this._sectionToolContextMenu.on("shown",(()=>{this._menuButtonArrowElement.classList.remove("xeokit-arrow-down"),this._menuButtonArrowElement.classList.add("xeokit-arrow-up")})),this._sectionToolContextMenu.on("hidden",(()=>{this._menuButtonArrowElement.classList.remove("xeokit-arrow-up"),this._menuButtonArrowElement.classList.add("xeokit-arrow-down")})),this.bimViewer.on("reset",(()=>{this.clear(),this.setActive(!1)})),this.viewer.scene.on("sectionPlaneCreated",(()=>{this._updateSectionPlanesCount()})),this.viewer.scene.on("sectionPlaneDestroyed",(()=>{this._updateSectionPlanesCount()})),this._initSectionMode()}_initSectionMode(){this.viewer.scene.input.on("mouseclicked",(e=>{if(!this.getActive()||!this.getEnabled())return;const t=this.viewer.scene.pick({canvasPos:e,pickSurface:!0});if(t){const e=this._sectionPlanesPlugin.createSectionPlane({pos:t.worldPos,dir:u.mulVec3Scalar(t.worldNormal,-1)});this._sectionPlanesPlugin.showControl(e.id)}})),this._updateSectionPlanesCount()}_updateSectionPlanesCount(){this._counterElement&&(this._counterElement.innerText=""+this.getNumSections())}getNumSections(){return Object.keys(this.viewer.scene.sectionPlanes).length}clear(){this._sectionPlanesPlugin.clear(),this._updateSectionPlanesCount()}flipSections(){this._sectionPlanesPlugin.flipSectionPlanes()}hideControl(){this._sectionPlanesPlugin.hideControl()}destroy(){this._sectionPlanesPlugin.destroy(),this._sectionToolContextMenu.destroy(),super.destroy()}}class Xn extends Ln{constructor(e,t){if(super(e,t),!t.navCubeCanvasElement)throw"Missing config: navCubeCanvasElement";const i=t.navCubeCanvasElement;this._navCube=new zo(this.viewer,{canvasElement:i,fitVisible:!0,color:"#CFCFCF"}),this._navCube.setVisible(this._active),this.on("active",(e=>{this._navCube.setVisible(e)}))}destroy(){this._navCube.destroy(),super.destroy()}}const Hn={IfcSpace:{opacity:.3},IfcWindow:{opacity:.4},IfcOpeningElement:{opacity:.3},IfcPlate:{opacity:.3}},Wn={IfcRoof:{colorize:[.837255,.203922,.270588],priority:0},IfcSlab:{colorize:[.637255,.603922,.670588],priority:0},IfcWall:{colorize:[.537255,.337255,.237255],priority:0},IfcWallStandardCase:{colorize:[.537255,.337255,.237255],priority:0},IfcCovering:{colorize:[.8470588235,.427450980392,0],priority:0},IfcDoor:{colorize:[.637255,.603922,.670588],priority:1},IfcStair:{colorize:[.637255,.603922,.670588],priority:2},IfcStairFlight:{colorize:[.637255,.603922,.670588],priority:2},IfcProxy:{colorize:[.137255,.403922,.870588],priority:2},IfcRamp:{colorize:[.8470588235,.427450980392,0],priority:2},IfcColumn:{colorize:[.137255,.403922,.870588],priority:3},IfcBeam:{colorize:[.137255,.403922,.870588],priority:3},IfcCurtainWall:{colorize:[.137255,.403922,.870588],priority:3},IfcPlate:{colorize:[.8470588235,.427450980392,0,.5],opacity:.5,priority:3},IfcTransportElement:{colorize:[.8470588235,.427450980392,0],priority:3},IfcFooting:{colorize:[.8470588235,.427450980392,0],priority:3},IfcRailing:{colorize:[.137255,.403922,.870588],priority:4},IfcFurnishingElement:{colorize:[.137255,.403922,.870588],priority:4},IfcFurniture:{colorize:[.8470588235,.427450980392,0],priority:4},IfcSystemFurnitureElement:{colorize:[.8470588235,.427450980392,0],priority:4},IfcFlowSegment:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowitting:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowTerminal:{colorize:[.137255,.403922,.870588],priority:5},IfcFlowController:{colorize:[.8470588235,.427450980392,0],priority:5},IfcFlowFitting:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDuctSegment:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDistributionFlowElement:{colorize:[.8470588235,.427450980392,0],priority:5},IfcDuctFitting:{colorize:[.8470588235,.427450980392,0],priority:5},IfcLightFixture:{colorize:[.8470588235,.8470588235,.870588],priority:5},IfcAirTerminal:{colorize:[.8470588235,.427450980392,0],priority:6},IfcOpeningElement:{colorize:[.137255,.403922,.870588],opacity:.3,priority:6},IfcSpace:{colorize:[.137255,.403922,.870588],opacity:.5,priority:6},IfcWindow:{colorize:[.137255,.403922,.870588],opacity:.4,priority:6},IfcBuildingElementProxy:{colorize:[.5,.5,.5]},IfcSite:{colorize:[.137255,.403922,.870588]},IfcMember:{colorize:[.8470588235,.427450980392,0]},DEFAULT:{colorize:[.5,.5,.5],priority:10}};class Yn extends o{constructor(e={}){const t=[[{title:"Load",getEnabled:function(e){return!e.bimViewer.isModelLoaded(e.modelId)},doAction:function(e){e.bimViewer.loadModel(e.modelId)}},{title:"Unload",getEnabled:function(e){return e.bimViewer.isModelLoaded(e.modelId)},doAction:function(e){e.bimViewer.unloadModel(e.modelId)}}]];!!e.enableEditModels&&t.push([{title:"Edit",getEnabled:function(e){return!0},doAction:function(e){e.bimViewer.editModel(e.modelId)}},{title:"Delete",getEnabled:function(e){return!0},doAction:function(e){e.bimViewer.deleteModel(e.modelId)}}]),t.push([{title:"Load All",getEnabled:function(e){const t=e.bimViewer,i=t.getModelIds();return t.getLoadedModelIds().length<i.length},doAction:function(e){e.bimViewer.loadAllModels()}},{title:"Unload All",getEnabled:function(e){return e.bimViewer.getLoadedModelIds().length>0},doAction:function(e){e.bimViewer.unloadAllModels()}}]),t.push([{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]),super({context:e.context,items:t})}}const qn=u.vec3();class Kn extends Ln{constructor(e,t){if(super(e,t),!t.modelsTabElement)throw"Missing config: modelsTabElement";if(!t.unloadModelsButtonElement)throw"Missing config: unloadModelsButtonElement";if(!t.modelsElement)throw"Missing config: modelsElement";if(this._enableAddModels=!!t.enableEditModels,this._modelsTabElement=t.modelsTabElement,this._loadModelsButtonElement=t.loadModelsButtonElement,this._unloadModelsButtonElement=t.unloadModelsButtonElement,this._addModelButtonElement=t.addModelButtonElement,this._modelsElement=t.modelsElement,this._modelsTabButtonElement=this._modelsTabElement.querySelector(".xeokit-tab-btn"),!this._modelsTabButtonElement)throw"Missing DOM element: ,xeokit-tab-btn";this._xktLoader=new Da(this.viewer,{objectDefaults:Hn}),this._modelsContextMenu=new Yn({enableEditModels:t.enableEditModels}),this._modelsInfo={},this._numModels=0,this._numModelsLoaded=0,this._projectId=null}loadProject(e,t,i){this.server.getProject(e,(i=>{this.unloadProject(),this._projectId=e,this._modelsInfo={},this._numModels=0,this._parseProject(i,t),this._numModelsLoaded<this._numModels&&this._loadModelsButtonElement.classList.remove("disabled"),this._numModelsLoaded>0&&this._unloadModelsButtonElement.classList.remove("disabled"),this._enableAddModels&&this._addModelButtonElement.classList.remove("disabled")}),(e=>{this.error(e),i&&i(e)}))}_parseProject(e,t){this._buildModelsMenu(e),this._parseViewerConfigs(e),this._parseViewerContent(e,(()=>{this._parseViewerState(e,(()=>{t()}))}))}_buildModelsMenu(e){var t="";const i=e.models||[];this._modelsInfo={},this._numModels=i.length;for(let e=0,s=i.length;e<s;e++){const s=i[e];this._modelsInfo[s.id]=s,t+="<div class='xeokit-form-check'>",t+="<input id='"+s.id+"' type='checkbox' value=''><span id='span-"+s.id+"' class='disabled'>"+s.name+"</span>",t+="</div>"}this._modelsElement.innerHTML=t;for(let e=0,t=i.length;e<t;e++){const t=i[e],s=t.id,r=document.getElementById(""+s),o=document.getElementById("span-"+s);r.addEventListener("click",(()=>{r.checked?this.loadModel(s):this.unloadModel(t.id)})),o.addEventListener("click",(()=>{!!this.viewer.scene.models[s]?this.unloadModel(t.id):this.loadModel(s)})),o.oncontextmenu=e=>{this._modelsContextMenu.context={bimViewer:this.bimViewer,viewer:this.viewer,modelId:s},this._modelsContextMenu.show(e.pageX,e.pageY),e.preventDefault()}}}_parseViewerConfigs(e){const t=e.viewerConfigs;t&&this.bimViewer.setConfigs(t)}_parseViewerContent(e,t){const i=e.viewerContent;i?this._parseModelsLoaded(i,(()=>{t()})):t()}_parseModelsLoaded(e,t){const i=e.modelsLoaded;i&&0!==i.length?this._loadNextModel(i.slice(0),t):t()}_loadNextModel(e,t){if(0===e.length)return void t();const i=e.pop();this.loadModel(i,(()=>{this._loadNextModel(e,t)}),(()=>{this._loadNextModel(e,t)}))}_parseViewerState(e,t){const i=e.viewerState;i?this.bimViewer.setViewerState(i,t):t()}unloadProject(){if(!this._projectId)return;const e=this.viewer.scene.models;for(var t in e)if(e.hasOwnProperty(t)){e[t].destroy()}this._modelsElement.innerHTML="",this._numModelsLoaded=0,this._loadModelsButtonElement.classList.add("disabled"),this._unloadModelsButtonElement.classList.add("disabled"),this._enableAddModels&&this._addModelButtonElement.classList.add("disabled");const i=this._projectId;this._projectId=null,this.fire("projectUnloaded",{projectId:i})}getLoadedProjectId(){return this._projectId}getModelIds(){return Object.keys(this._modelsInfo)}loadModel(e,t,i){if(!this._projectId){const e="No project currently loaded";return this.error(e),void(i&&i(e))}const s=this._modelsInfo[e];if(!s){const e="Model not in currently loaded project";return this.error(e),void(i&&i(e))}this.bimViewer._busyModal.show("Loading: "+s.name);this.bimViewer.getConfig("externalMetadata")?this.server.getMetadata(this._projectId,e,(r=>{this._loadGeometry(e,s,r,t,i)}),(e=>{this.bimViewer._busyModal.hide(),this.error(e),i&&i(e)})):this._loadGeometry(e,s,null,t,i)}_loadGeometry(e,t,i,s,r){this.server.getGeometry(this._projectId,e,(r=>{const o="model"===(t.objectColorSource||this.bimViewer.getObjectColorSource())?Hn:Wn;this._xktLoader.load({id:e,metaModelData:i,xkt:r,objectDefaults:o,excludeUnclassifiedObjects:!0,position:t.position,scale:t.scale,rotation:t.rotation,matrix:t.matrix,edges:!1!==t.edges,saoEnabled:t.saoEnabled,pbrEnabled:t.pbrEnabled,backfaces:t.backfaces,excludeTypes:["IfcSpace"]}).on("loaded",(()=>{document.getElementById(""+e).checked=!0;const t=this.viewer.scene,i=t.getAABB(t.visibleObjectIds);this._numModelsLoaded++,this._unloadModelsButtonElement.classList.remove("disabled"),this._numModelsLoaded<this._numModels?this._loadModelsButtonElement.classList.remove("disabled"):this._loadModelsButtonElement.classList.add("disabled"),1===this._numModelsLoaded?(this.viewer.cameraFlight.jumpTo({aabb:i}),this.viewer.cameraControl.pivotPos=u.getAABB3Center(i,qn),this.fire("modelLoaded",e),this.bimViewer._busyModal.hide(),s&&s()):(this.fire("modelLoaded",e),this.bimViewer._busyModal.hide(),s&&s())}))}),(e=>{this.bimViewer._busyModal.hide(),this.error(e),r&&r(e)}))}unloadModel(e){const t=this.viewer.scene.models[e];if(!t)return void this.error("Model not loaded: "+e);t.destroy();document.getElementById(""+e).checked=!1;document.getElementById("span-"+e);this._numModelsLoaded--,this._numModelsLoaded>0?this._unloadModelsButtonElement.classList.remove("disabled"):this._unloadModelsButtonElement.classList.add("disabled"),this._numModelsLoaded<this._numModels?this._loadModelsButtonElement.classList.remove("disabled"):this._loadModelsButtonElement.classList.add("disabled"),this.fire("modelUnloaded",e)}unloadAllModels(){const e=this.viewer.scene.models,t=Object.keys(e);for(var i=0,s=t.length;i<s;i++){const e=t[i];this.unloadModel(e)}}getNumModelsLoaded(){return this._numModelsLoaded}_getLoadedModelIds(){return Object.keys(this.viewer.scene.models)}isModelLoaded(e){return!!this.viewer.scene.models[e]}getModelsInfo(){return this._modelsInfo}getModelInfo(e){return this._modelsInfo[e]}setEnabled(e){e?(this._modelsTabButtonElement.classList.remove("disabled"),this._unloadModelsButtonElement.classList.remove("disabled")):(this._modelsTabButtonElement.classList.add("disabled"),this._unloadModelsButtonElement.classList.add("disabled"))}destroy(){super.destroy(),this._xktLoader.destroy()}}const Zn=u.vec3();class Qn extends o{constructor(e={}){super({context:e.context,items:[[{title:"View Fit",doAction:function(e){const t=e.viewer,i=t.scene,s=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,(e=>{e.objectId&&s.push(e.objectId)})),i.setObjectsVisible(s,!0),i.setObjectsHighlighted(s,!0);const r=i.getAABB(s);t.cameraFlight.flyTo({aabb:r,duration:.5},(()=>{setTimeout((function(){i.setObjectsHighlighted(i.highlightedObjectIds,!1)}),500)})),t.cameraControl.pivotPos=u.getAABB3Center(r)}},{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=u.getAABB3Center(s)}}],[{title:"Isolate",doAction:function(e){const t=e.viewer,i=t.scene,s=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,(e=>{e.objectId&&s.push(e.objectId)}));const r=i.getAABB(s);t.cameraControl.pivotPos=u.getAABB3Center(r,Zn),i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsVisible(i.visibleObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsVisible(s,!0),t.cameraFlight.flyTo({aabb:r},(()=>{}))}}],[{title:"Hide",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,(t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.visible=!1)}}))}},{title:"Hide Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.visibleObjectIds,!1),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,(e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.visible=!0)}}))}},{title:"Hide All",getEnabled:function(e){return e.viewer.scene.visibleObjectIds.length>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}}],[{title:"Show",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,(t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.visible=!0,i.xrayed&&(i.pickable=!0),i.xrayed=!1,i.selected=!1)}}))}},{title:"Show Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,(e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.visible=!1)}}))}},{title:"Show All",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects<t.numObjects||e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"X-Ray",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,(t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.selected=!1,i.xrayed=!0,i.visible=!0,i.pickable=!1)}}))}},{title:"Undo X-Ray",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,(t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.xrayed=!1,i.pickable=!0)}}))}},{title:"X-Ray Others",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsSelected(t.selectedObjectIds,!1),e.treeViewPlugin.withNodeTree(e.treeViewNode,(e=>{if(e.objectId){const i=t.objects[e.objectId];i&&(i.xrayed=!1,i.pickable=!0)}}))}},{title:"X-Ray All",doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsSelected(t.selectedObjectIds,!1),t.setObjectsPickable(t.objectIds,!1)}},{title:"X-Ray None",getEnabled:function(e){return e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene,i=t.xrayedObjectIds;t.setObjectsPickable(i,!0),t.setObjectsXRayed(i,!1)}}],[{title:"Select",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,(t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.selected=!0,i.visible=!0)}}))}},{title:"Undo Select",doAction:function(e){e.treeViewPlugin.withNodeTree(e.treeViewNode,(t=>{if(t.objectId){const i=e.viewer.scene.objects[t.objectId];i&&(i.selected=!1)}}))}},{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}class $n extends Ln{constructor(e,t={}){if(super(e),!t.objectsTabElement)throw"Missing config: objectsTabElement";if(!t.showAllObjectsButtonElement)throw"Missing config: showAllObjectsButtonElement";if(!t.hideAllObjectsButtonElement)throw"Missing config: hideAllObjectsButtonElement";if(!t.objectsElement)throw"Missing config: objectsElement";if(this._objectsTabElement=t.objectsTabElement,this._showAllObjectsButtonElement=t.showAllObjectsButtonElement,this._hideAllObjectsButtonElement=t.hideAllObjectsButtonElement,this._objectsTabButtonElement=this._objectsTabElement.querySelector(".xeokit-tab-btn"),!this._objectsTabButtonElement)throw"Missing DOM element: ,xeokit-tab-btn";const i=t.objectsElement;this._treeView=new ta(this.viewer,{containerElement:i,hierarchy:"containment",autoAddModels:!1,pruneEmptyNodes:!0}),this._treeViewContextMenu=new Qn,this._treeView.on("contextmenu",(e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)})),this._treeView.on("nodeTitleClicked",(e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,(e=>{e.objectId&&i.push(e.objectId)}));e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))})),this._onModelLoaded=this.viewer.scene.on("modelLoaded",(e=>{if(this.viewer.metaScene.metaModels[e]){const t=this.bimViewer._modelsExplorer.getModelInfo(e);if(!t)return;this._treeView.addModel(e,{rootName:t.name})}})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)})),this.bimViewer.on("reset",(()=>{this._treeView.collapse()}))}setEnabled(e){e?(this._objectsTabButtonElement.classList.remove("disabled"),this._showAllObjectsButtonElement.classList.remove("disabled"),this._hideAllObjectsButtonElement.classList.remove("disabled")):(this._objectsTabButtonElement.classList.add("disabled"),this._showAllObjectsButtonElement.classList.add("disabled"),this._hideAllObjectsButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}u.vec3();class Jn extends Ln{constructor(e,t={}){if(super(e),!t.classesTabElement)throw"Missing config: classesTabElement";if(!t.showAllClassesButtonElement)throw"Missing config: showAllClassesButtonElement";if(!t.hideAllClassesButtonElement)throw"Missing config: hideAllClassesButtonElement";if(!t.classesElement)throw"Missing config: classesElement";if(this._classesTabElement=t.classesTabElement,this._showAllClassesButtonElement=t.showAllClassesButtonElement,this._hideAllClassesButtonElement=t.hideAllClassesButtonElement,this._classesTabButtonElement=this._classesTabElement.querySelector(".xeokit-tab-btn"),!this._classesTabButtonElement)throw"Missing DOM element: xeokit-tab-btn";const i=t.classesElement;this._treeView=new ta(this.viewer,{containerElement:i,hierarchy:"types",autoAddModels:!1,pruneEmptyNodes:!0}),this._treeViewContextMenu=new Qn,this._treeView.on("contextmenu",(e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)})),this._treeView.on("nodeTitleClicked",(e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,(e=>{e.objectId&&i.push(e.objectId)}));e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))})),this._onModelLoaded=this.viewer.scene.on("modelLoaded",(e=>{if(this.viewer.metaScene.metaModels[e]){const t=this.bimViewer._modelsExplorer.getModelInfo(e);if(!t)return;this._treeView.addModel(e,{rootName:t.name})}})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)})),this.bimViewer.on("reset",(()=>{this._treeView.collapse()}))}setEnabled(e){e?(this._classesTabButtonElement.classList.remove("disabled"),this._showAllClassesButtonElement.classList.remove("disabled"),this._hideAllClassesButtonElement.classList.remove("disabled")):(this._classesTabButtonElement.classList.add("disabled"),this._showAllClassesButtonElement.classList.add("disabled"),this._hideAllClassesButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const el=u.vec3();class tl extends Ln{constructor(e,t={}){if(super(e),!t.storeysTabElement)throw"Missing config: storeysTabElement";if(!t.showAllStoreysButtonElement)throw"Missing config: showAllStoreysButtonElement";if(!t.hideAllStoreysButtonElement)throw"Missing config: hideAllStoreysButtonElement";if(!t.storeysElement)throw"Missing config: storeysElement";if(this._storeysTabElement=t.storeysTabElement,this._showAllStoreysButtonElement=t.showAllStoreysButtonElement,this._hideAllStoreysButtonElement=t.hideAllStoreysButtonElement,this._storeysTabButtonElement=this._storeysTabElement.querySelector(".xeokit-tab-btn"),!this._storeysTabButtonElement)throw"Missing DOM element: .xeokit-tab-btn";const i=t.storeysElement;this._treeView=new ta(this.viewer,{containerElement:i,autoAddModels:!1,hierarchy:"storeys",autoExpandDepth:1}),this._treeViewContextMenu=new Qn,this._treeView.on("contextmenu",(e=>{this._treeViewContextMenu.context={bimViewer:this.bimViewer,viewer:e.viewer,treeViewPlugin:e.treeViewPlugin,treeViewNode:e.treeViewNode,pruneEmptyNodes:!0},this._treeViewContextMenu.show(e.event.pageX,e.event.pageY)})),this._treeView.on("nodeTitleClicked",(e=>{const t=this.viewer.scene,i=[];e.treeViewPlugin.withNodeTree(e.treeViewNode,(e=>{e.objectId&&i.push(e.objectId)}));e.treeViewNode.checked?(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!1),t.setObjectsPickable(i,!0)):(t.setObjectsXRayed(i,!1),t.setObjectsVisible(i,!0),t.setObjectsPickable(i,!0))})),this._onModelLoaded=this.viewer.scene.on("modelLoaded",(e=>{const t=this.bimViewer._modelsExplorer.getModelInfo(e);t&&this._treeView.addModel(e,{rootName:t.name})})),this._onModelUnloaded=this.viewer.scene.on("modelUnloaded",(e=>{this.viewer.metaScene.metaModels[e]&&this._treeView.removeModel(e)})),this.bimViewer.on("reset",(()=>{this._treeView.collapse(),this._treeView.expandToDepth(1)}))}setEnabled(e){e?(this._storeysTabButtonElement.classList.remove("disabled"),this._showAllStoreysButtonElement.classList.remove("disabled"),this._hideAllStoreysButtonElement.classList.remove("disabled")):(this._storeysTabButtonElement.classList.add("disabled"),this._showAllStoreysButtonElement.classList.add("disabled"),this._hideAllStoreysButtonElement.classList.add("disabled"))}expandTreeViewToDepth(e){this._treeView.expandToDepth(e)}showNodeInTreeView(e){this._treeView.collapse(),this._treeView.showNode(e)}unShowNodeInTreeView(){this._treeView.unShowNode()}selectStorey(e,t){const i=this.viewer.metaScene.metaObjects[e];if(!i)return void this.error("selectStorey() - object is not found: '"+e+"'");if("IfcBuildingStorey"!==i.type)return void this.error("selectStorey() - object is not found: '"+e+"'");const s=i.getObjectIDsInSubtree();this._selectObjects(s,t)}_selectObjects(e,t){const i=this.viewer.scene,s=i.getAABB(e);this.viewer.cameraControl.pivotPos=u.getAABB3Center(s,el),t?(i.setObjectsXRayed(i.objectIds,!0),i.setObjectsVisible(i.objectIds,!0),i.setObjectsPickable(i.objectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsXRayed(e,!1),i.setObjectsVisible(e,!0),i.setObjectsPickable(e,!0),this.viewer.cameraFlight.flyTo({aabb:s},(()=>{setTimeout((function(){i.setObjectsVisible(i.xrayedObjectIds,!1),i.setObjectsXRayed(i.xrayedObjectIds,!1)}),500),t()}))):(i.setObjectsVisible(i.objectIds,!1),i.setObjectsPickable(i.xrayedObjectIds,!0),i.setObjectsXRayed(i.xrayedObjectIds,!1),i.setObjectsSelected(i.selectedObjectIds,!1),i.setObjectsVisible(e,!0),this.viewer.cameraFlight.jumpTo({aabb:s}))}destroy(){super.destroy(),this._treeView.destroy(),this._treeViewContextMenu.destroy(),this.viewer.scene.off(this._onModelLoaded),this.viewer.scene.off(this._onModelUnloaded)}}const il=u.vec3();class sl extends Ln{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";this._saveOrthoActive=null,this._buttonElement=t.buttonElement,this._cameraControlNavModeMediator=t.cameraControlNavModeMediator,this._active=!1,this.on("enabled",(e=>{e?this._buttonElement.classList.remove("disabled"):this._buttonElement.classList.add("disabled")})),this._buttonElement.addEventListener("click",(e=>{this.getEnabled()&&(this.bimViewer._sectionTool.hideControl(),this.setActive(!this.getActive(),(()=>{}))),e.preventDefault()})),this.bimViewer.on("reset",(()=>{this.setActive(!0,(()=>{}))}))}setEnabled(e){super.setEnabled(e),this._saveOrthoActive=this.bimViewer._orthoMode.getActive()}setActive(e,t){this._active!==e?(this._active=e,e?(this._buttonElement.classList.add("active"),t?this._enterThreeDMode((()=>{this.fire("active",this._active),t()})):(this._enterThreeDMode(),this.fire("active",this._active))):(this._buttonElement.classList.remove("active"),t?this._exitThreeDMode((()=>{this.fire("active",this._active),t()})):(this._exitThreeDMode(),this.fire("active",this._active)))):t&&t()}_enterThreeDMode(e){const t=this.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds),r=u.getAABB3Diag(s),o=u.getAABB3Center(s,il),a=Math.abs(r/Math.tan(32.5)),n=i.camera,l=n.yUp?[-1,-1,-1]:[1,1,1],h=n.yUp?[-1,1,-1]:[-1,1,1];t.cameraControl.pivotPos=o,this.bimViewer._navCubeMode.setActive(!0),this.bimViewer._firstPersonMode.setEnabled(!0),this._cameraControlNavModeMediator.setThreeDModeActive(!0),this.bimViewer._sectionTool.setEnabled(!0),this.bimViewer._orthoMode.setEnabled(!0),e?t.cameraFlight.flyTo({look:o,eye:[o[0]-a*l[0],o[1]-a*l[1],o[2]-a*l[2]],up:h,orthoScale:1.3*r,duration:1,projection:this._saveOrthoActive?"ortho":"perspective"},(()=>{e()})):t.cameraFlight.jumpTo({look:o,eye:[o[0]-a*l[0],o[1]-a*l[1],o[2]-a*l[2]],up:h,orthoScale:1.3*r,projection:this._saveOrthoActive?"ortho":"perspective"})}_exitThreeDMode(e){const t=this.viewer,i=t.scene,s=i.camera,r=i.getAABB(i.visibleObjectIds),o=u.getAABB3Center(r),a=u.getAABB3Diag(r),n=Math.abs(a/Math.tan(45*u.DEGTORAD)),l=1.3*a,h=il;h[0]=o[0]+s.worldUp[0]*n,h[1]=o[1]+s.worldUp[1]*n,h[2]=o[2]+s.worldUp[2]*n;const c=u.mulVec3Scalar(s.worldForward,-1,[]);this.bimViewer._sectionTool.setActive(!1),this.bimViewer._firstPersonMode.setEnabled(!1),this._saveOrthoActive=this.bimViewer._orthoMode.getActive(),this.bimViewer._orthoMode.setEnabled(!1),this._cameraControlNavModeMediator.setThreeDModeActive(!1),e?t.cameraFlight.flyTo({eye:h,look:o,up:c,orthoScale:l,projection:"ortho"},(()=>{this.bimViewer._navCubeMode.setActive(!1)})):(t.cameraFlight.jumpTo({eye:h,look:o,up:c,orthoScale:l,projection:"ortho"}),this.bimViewer._navCubeMode.setActive(!1))}}class rl extends o{constructor(e={}){super({context:e.context,items:[[{title:"View Fit",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity;t.cameraFlight.flyTo({aabb:s.aabb,duration:.5},(()=>{setTimeout((function(){i.setObjectsHighlighted(i.highlightedObjectIds,!1)}),500)})),t.cameraControl.pivotPos=u.getAABB3Center(s.aabb)}},{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=u.getAABB3Center(s)}},{title:"Show in Tree",doAction:function(e){const t=e.entity.id;e.showObjectInExplorers(t)}}],[{title:"Hide",getEnabled:function(e){return e.entity.visible},doAction:function(e){e.entity.visible=!1}},{title:"Hide Others",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity,r=t.metaScene.metaObjects[s.id];r&&(i.setObjectsVisible(i.visibleObjectIds,!1),r.withMetaObjectsInSubtree((e=>{const t=i.objects[e.id];t&&(t.visible=!0)})))}},{title:"Hide All",getEnabled:function(e){return e.viewer.scene.numVisibleObjects>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}},{title:"Show All",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects<t.numObjects||e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.xrayedObjectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"X-Ray",getEnabled:function(e){return!e.entity.xrayed},doAction:function(e){const t=e.entity;t.xrayed=!0,t.pickable=!1}},{title:"X-Ray Others",doAction:function(e){const t=e.viewer,i=t.scene,s=e.entity,r=t.metaScene.metaObjects[s.id];r&&(i.setObjectsVisible(i.objectIds,!0),i.setObjectsXRayed(i.objectIds,!0),i.setObjectsPickable(i.objectIds,!1),r.withMetaObjectsInSubtree((e=>{const t=i.objects[e.id];t&&(t.xrayed=!1,t.pickable=!0)})))}},{title:"X-Ray All",getEnabled:function(e){const t=e.viewer.scene;return t.numXRayedObjects<t.numObjects},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1),t.setObjectsXRayed(t.objectIds,!0)}},{title:"X-Ray None",getEnabled:function(e){return e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene,i=t.xrayedObjectIds;t.setObjectsPickable(i,!0),t.setObjectsXRayed(i,!1)}}],[{title:"Select",getEnabled:function(e){return!e.entity.selected},doAction:function(e){e.entity.selected=!0}},{title:"Undo Select",getEnabled:function(e){return e.entity.selected},doAction:function(e){e.entity.selected=!1}},{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}class ol extends o{constructor(e={}){super({context:e.context,items:[[{title:"View Fit All",doAction:function(e){const t=e.viewer,i=t.scene,s=i.getAABB(i.visibleObjectIds);t.cameraFlight.flyTo({aabb:s,duration:.5}),t.cameraControl.pivotPos=u.getAABB3Center(s)}}],[{title:"Hide All",getEnabled:function(e){return e.viewer.scene.numVisibleObjects>0},doAction:function(e){e.viewer.scene.setObjectsVisible(e.viewer.scene.visibleObjectIds,!1)}},{title:"Show all",getEnabled:function(e){const t=e.viewer.scene;return t.numVisibleObjects<t.numObjects||e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.xrayedObjectIds,!1)}}],[{title:"X-Ray All",getEnabled:function(e){const t=e.viewer.scene;return t.numXRayedObjects<t.numObjects},doAction:function(e){const t=e.viewer.scene;t.setObjectsVisible(t.objectIds,!0),t.setObjectsXRayed(t.objectIds,!0),t.setObjectsPickable(t.objectIds,!1)}},{title:"X-Ray None",getEnabled:function(e){return e.viewer.scene.numXRayedObjects>0},doAction:function(e){const t=e.viewer.scene.xrayedObjectIds;e.viewer.scene.setObjectsPickable(t,!0),e.viewer.scene.setObjectsXRayed(t,!1)}}],[{title:"Select None",getEnabled:function(e){return e.viewer.scene.numSelectedObjects>0},doAction:function(e){e.viewer.scene.setObjectsSelected(e.viewer.scene.selectedObjectIds,!1)}}],[{title:"Reset View",doAction:function(e){e.bimViewer.resetView()}}],[{title:"Clear Slices",getEnabled:function(e){return e.bimViewer.getNumSections()>0},doAction:function(e){e.bimViewer.clearSections()}}]]})}}class al extends Ln{constructor(e,t){if(super(e,t),!t.buttonElement)throw"Missing config: buttonElement";this._buttonElement=t.buttonElement,this.on("enabled",(e=>{e?this._buttonElement.classList.remove("disabled"):this._buttonElement.classList.add("disabled")})),this._buttonElement.addEventListener("click",(e=>{this.getEnabled()&&this.setActive(!this.getActive()),e.preventDefault()})),this.bimViewer.on("reset",(()=>{this.setActive(!1)})),this._active=!1,this._buttonElement.classList.remove("active")}setActive(e,t){this._active!==e?(this._active=e,e?(this._buttonElement.classList.add("active"),t?this._enterOrthoMode((()=>{this.fire("active",this._active),t()})):(this._enterOrthoMode(),this.fire("active",this._active))):(this._buttonElement.classList.remove("active"),t?this._exitOrthoMode((()=>{this.fire("active",this._active),t()})):(this._exitOrthoMode(),this.fire("active",this._active)))):t&&t()}_enterOrthoMode(e){this.viewer.cameraFlight.flyTo({projection:"ortho",duration:.5},e)}_exitOrthoMode(e){this.viewer.cameraFlight.flyTo({projection:"perspective",duration:.5},e)}}class nl extends Ln{constructor(e,t={}){if(!t.canvasElement)throw"Config expected: canvasElement";if(!t.explorerElement)throw"Config expected: explorerElement";if(!t.toolbarElement)throw"Config expected: toolbarElement";if(!t.navCubeCanvasElement)throw"Config expected: navCubeCanvasElement";const i=t.canvasElement,s=t.explorerElement,r=t.toolbarElement,o=t.navCubeCanvasElement,a=t.queryInfoPanelElement,n=t.busyModelBackdropElement;s.oncontextmenu=e=>{e.preventDefault()},r.oncontextmenu=e=>{e.preventDefault()},o.oncontextmenu=e=>{e.preventDefault()};const l=new Cn({canvasElement:i,transparent:!1,backgroundColor:[1,1,1],backgroundColorFromAmbientLight:!1,saoEnabled:!0,pbrEnabled:!0});super(null,t,e,l),this._configs={},this.viewer=l,this._customizeViewer(),this._initCanvasContextMenus(),this._enableAddModels=!!t.enableEditModels,s.innerHTML=function(e){return'<div class="xeokit-tabs">\n    <div class="xeokit-tab xeokit-modelsTab">\n        <a class="xeokit-tab-btn" href="#">Models</a>\n        <div class="xeokit-tab-content">\n            <div class="xeokit-btn-group">\n                <button type="button" class="xeokit-loadAllModels xeokit-btn disabled" data-tippy-content="Load all models">Load all</button>\n                <button type="button" class="xeokit-unloadAllModels xeokit-btn disabled" data-tippy-content="Unload all models">Unload all</button>'+(e.enableEditModels?'<button type="button" class="xeokit-addModel xeokit-btn disabled" data-tippy-content="Add model">Add</button>':"")+'</div>\n            <div class="xeokit-models" ></div>\n        </div>\n    </div>\n    <div class="xeokit-tab xeokit-objectsTab">\n        <a class="xeokit-tab-btn disabled" href="#">Objects</a>\n        <div class="xeokit-tab-content">\n         <div class="xeokit-btn-group">\n            <button type="button" class="xeokit-showAllObjects xeokit-btn disabled" data-tippy-content="Show all objects">Show all</button>\n            <button type="button" class="xeokit-hideAllObjects xeokit-btn disabled" data-tippy-content="Hide all objects">Hide all</button>\n        </div>\n        <div class="xeokit-objects xeokit-tree-panel" ></div>\n        </div>\n    </div>\n    <div class="xeokit-tab xeokit-classesTab">\n        <a class="xeokit-tab-btn disabled" href="#">Classes</a>\n        <div class="xeokit-tab-content">\n            <div class="xeokit-btn-group">\n                <button type="button" class="xeokit-showAllClasses xeokit-btn disabled" data-tippy-content="Show all classes">Show all</button>\n                <button type="button" class="xeokit-hideAllClasses xeokit-btn disabled" data-tippy-content="Hide all classes">Hide all</button>\n            </div>\n            <div class="xeokit-classes xeokit-tree-panel" ></div>\n        </div>\n    </div>\n     <div class="xeokit-tab xeokit-storeysTab">\n        <a class="xeokit-tab-btn disabled" href="#">Storeys</a>\n        <div class="xeokit-tab-content">\n         <div class="xeokit-btn-group">\n                <button type="button" class="xeokit-showAllStoreys xeokit-btn disabled" data-tippy-content="Show all storeys">Show all</button>\n                <button type="button" class="xeokit-hideAllStoreys xeokit-btn disabled" data-tippy-content="Hide all storeys">Hide all</button>\n            </div>\n             <div class="xeokit-storeys xeokit-tree-panel"></div>\n        </div>\n    </div>\n</div>'}(t),r.innerHTML='<div class="xeokit-toolbar">\n    \x3c!-- Reset button --\x3e\n    <div class="xeokit-btn-group">\n        <button type="button" class="xeokit-reset xeokit-btn fa fa-home fa-2x disabled" data-tippy-content="Reset view"></button>\n    </div>\n    <div class="xeokit-btn-group" role="group">\n        \x3c!-- 3D Mode button --\x3e\n        <button type="button" class="xeokit-threeD xeokit-btn fa fa-cube fa-2x disabled" data-tippy-content="Toggle 2D/3D"></button>\n        \x3c!-- Perspective/Ortho Mode button --\x3e\n        <button type="button" class="xeokit-ortho xeokit-btn fa fa-th fa-2x  disabled" data-tippy-content="Toggle Perspective/Ortho"></button>\n        \x3c!-- Fit button --\x3e\n        <button type="button" class="xeokit-fit xeokit-btn fa fa-crop fa-2x disabled" data-tippy-content="View fit"></button>   \n        \x3c!-- First Person mode button --\x3e\n        <button type="button" class="xeokit-firstPerson xeokit-btn fa fa-male fa-2x disabled" data-tippy-content="First person"></button>\n    </div>\n    \x3c!-- Tools button group --\x3e\n    <div class="xeokit-btn-group" role="group">\n        \x3c!-- Hide tool button --\x3e\n        <button type="button" class="xeokit-hide xeokit-btn fa fa-eraser fa-2x disabled" data-tippy-content="Hide objects"></button>\n        \x3c!-- Select tool button --\x3e\n        <button type="button" class="xeokit-select xeokit-btn fa fa-mouse-pointer fa-2x disabled" data-tippy-content="Select objects"></button>\n        \x3c!-- Query tool button --\x3e\n        <button type="button" class="xeokit-query xeokit-btn fa fa-info-circle fa-2x disabled" data-tippy-content="Query objects"></button>\n        \x3c!-- section tool button --\x3e\n        <button type="button" class="xeokit-section xeokit-btn fa fa-cut fa-2x disabled" data-tippy-content="Slice objects"><div class="xeokit-section-menu-button disabled" data-tippy-content="Slices menu"><span class="xeokit-arrow-down xeokit-section-menu-button-arrow"></span></div><div class="xeokit-section-counter" data-tippy-content="Number of existing slices"></div></button>\n    </div>\n\n</div>',this._explorerElement=s,function(e){const t="xeokit-tab",i="active";function s(e){let s=e.parentNode.querySelectorAll("."+t);for(let t=0;t<s.length;t++){let r=s[t];r.isEqualNode(e)?r.classList.add(i):r.classList.remove(i)}}let r=e.querySelectorAll(".xeokit-tabs");for(let e=0;e<r.length;e++){let i=r[e].querySelectorAll("."+t);s(i[0]);for(let e=0;e<i.length;e++)i[e].querySelector(".xeokit-tab-btn").addEventListener("click",(function(e){e.preventDefault(),this.classList.contains("disabled")||s(e.target.parentNode)}))}}(s),this._modelsExplorer=new Kn(this,{modelsTabElement:s.querySelector(".xeokit-modelsTab"),loadModelsButtonElement:s.querySelector(".xeokit-loadAllModels"),unloadModelsButtonElement:s.querySelector(".xeokit-unloadAllModels"),addModelButtonElement:s.querySelector(".xeokit-addModel"),modelsElement:s.querySelector(".xeokit-models"),enableEditModels:this._enableAddModels}),this._objectsExplorer=new $n(this,{objectsTabElement:s.querySelector(".xeokit-objectsTab"),showAllObjectsButtonElement:s.querySelector(".xeokit-showAllObjects"),hideAllObjectsButtonElement:s.querySelector(".xeokit-hideAllObjects"),objectsElement:s.querySelector(".xeokit-objects")}),this._classesExplorer=new Jn(this,{classesTabElement:s.querySelector(".xeokit-classesTab"),showAllClassesButtonElement:s.querySelector(".xeokit-showAllClasses"),hideAllClassesButtonElement:s.querySelector(".xeokit-hideAllClasses"),classesElement:s.querySelector(".xeokit-classes")}),this._storeysExplorer=new tl(this,{storeysTabElement:s.querySelector(".xeokit-storeysTab"),showAllStoreysButtonElement:s.querySelector(".xeokit-showAllStoreys"),hideAllStoreysButtonElement:s.querySelector(".xeokit-hideAllStoreys"),storeysElement:s.querySelector(".xeokit-storeys")}),this._resetAction=new Rn(this,{buttonElement:r.querySelector(".xeokit-reset"),active:!1}),this._fitAction=new Nn(this,{buttonElement:r.querySelector(".xeokit-fit"),active:!1});const h=new function(e){let t=!1;this.setThreeDModeActive=i=>{i?(e._firstPersonMode.setActive(!1),e.viewer.cameraControl.navMode="orbit"):(e._firstPersonMode.setActive(!1),e.viewer.cameraControl.navMode="planView"),t=i},this.setFirstPersonModeActive=i=>{e.viewer.cameraControl.navMode=i?"firstPerson":t?"orbit":"planView"}}(this);this._threeDMode=new sl(this,{buttonElement:r.querySelector(".xeokit-threeD"),cameraControlNavModeMediator:h,active:!1}),this._orthoMode=new al(this,{buttonElement:r.querySelector(".xeokit-ortho"),active:!1}),this._firstPersonMode=new In(this,{buttonElement:r.querySelector(".xeokit-firstPerson"),cameraControlNavModeMediator:h,active:!1}),this._hideTool=new On(this,{buttonElement:r.querySelector(".xeokit-hide"),active:!1}),this._selectionTool=new kn(this,{buttonElement:r.querySelector(".xeokit-select"),active:!1}),this._queryTool=new Vn(this,{buttonElement:r.querySelector(".xeokit-query"),queryInfoPanelElement:a,active:!1}),this._sectionTool=new Gn(this,{buttonElement:r.querySelector(".xeokit-section"),counterElement:r.querySelector(".xeokit-section-counter"),menuButtonElement:r.querySelector(".xeokit-section-menu-button"),menuButtonArrowElement:r.querySelector(".xeokit-section-menu-button-arrow"),active:!1}),this._navCubeMode=new Xn(this,{navCubeCanvasElement:o,active:!0}),this._busyModal=new Bn(this,{busyModalBackdropElement:n}),this._threeDMode.setActive(!0),this._firstPersonMode.setActive(!1),this._navCubeMode.setActive(!0),this._modelsExplorer.on("modelLoaded",(e=>{this._modelsExplorer.getNumModelsLoaded()>0&&this.setControlsEnabled(!0),this.fire("modelLoaded",e)})),this._modelsExplorer.on("modelUnloaded",(e=>{0===this._modelsExplorer.getNumModelsLoaded()&&(this.setControlsEnabled(!1),this.openTab("models")),this.fire("modelUnloaded",e)})),this._queryTool.on("queryPicked",(e=>{this.fire("queryPicked",e)})),this._queryTool.on("queryNotPicked",(()=>{this.fire("queryNotPicked",!0)})),this._resetAction.on("reset",(()=>{this.fire("reset",!0)})),this._mutexActivation([this._queryTool,this._hideTool,this._selectionTool,this._sectionTool]),s.querySelector(".xeokit-showAllObjects").addEventListener("click",(e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()})),s.querySelector(".xeokit-hideAllObjects").addEventListener("click",(e=>{this.setAllObjectsVisible(!1),e.preventDefault()})),s.querySelector(".xeokit-showAllClasses").addEventListener("click",(e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()})),s.querySelector(".xeokit-hideAllClasses").addEventListener("click",(e=>{this.setAllObjectsVisible(!1),e.preventDefault()})),s.querySelector(".xeokit-showAllStoreys").addEventListener("click",(e=>{this.setAllObjectsVisible(!0),this.setAllObjectsXRayed(!1),e.preventDefault()})),s.querySelector(".xeokit-hideAllStoreys").addEventListener("click",(e=>{this.setAllObjectsVisible(!1),e.preventDefault()})),s.querySelector(".xeokit-loadAllModels").addEventListener("click",(e=>{this.setControlsEnabled(!1),this.loadAllModels(),e.preventDefault()})),s.querySelector(".xeokit-unloadAllModels").addEventListener("click",(e=>{this.setControlsEnabled(!1),this._modelsExplorer.unloadAllModels(),e.preventDefault()})),this._enableAddModels&&s.querySelector(".xeokit-addModel").addEventListener("click",(e=>{this.fire("addModel",{}),e.preventDefault()})),this._bcfViewpointsPlugin=new ci(this.viewer,{}),this._fastNavPlugin=new fi(l,{}),this._initConfigs(),this.setControlsEnabled(!1)}_customizeViewer(){const e=this.viewer.scene;e.xrayMaterial.fill=!1,e.xrayMaterial.fillAlpha=.3,e.xrayMaterial.fillColor=[0,0,0],e.xrayMaterial.edges=!0,e.xrayMaterial.edgeAlpha=.1,e.xrayMaterial.edgeColor=[0,0,0],e.highlightMaterial.edges=!0,e.highlightMaterial.edgeColor=[1,1,0],e.highlightMaterial.edgeAlpha=.9,e.highlightMaterial.fill=!0,e.highlightMaterial.fillAlpha=.1,e.highlightMaterial.fillColor=[1,0,0],e.pointsMaterial.pointSize=1,e.pointsMaterial.roundPoints=!0,e.pointsMaterial.perspectivePoints=!0,e.pointsMaterial.minPerspectivePointSize=2,e.pointsMaterial.maxPerspectivePointSize=4,this.viewer.cameraControl.panRightClick=!0,this.viewer.cameraControl.followPointer=!0,this.viewer.cameraControl.doublePickFlyTo=!1,this.viewer.cameraControl.smartPivot=!0,this.viewer.cameraControl.keyboardDollyRate=100,this.viewer.cameraControl.mouseWheelDollyRate=100,this.viewer.cameraControl.dollyInertia=0,this.viewer.cameraControl.dollyMinSpeed=.04,this.viewer.cameraControl.dollyProximityThreshold=30;const t=document.createRange().createContextualFragment("<div class='xeokit-camera-pivot-marker'></div>").firstChild;document.body.appendChild(t),this.viewer.cameraControl.pivotElement=t,e.camera.perspective.near=.01,e.camera.perspective.far=3e3,e.camera.ortho.near=.01,e.camera.ortho.far=3e3;const i=e.sao;i.enabled=!0,i.numSamples=50,i.kernelRadius=200}_initCanvasContextMenus(){this._canvasContextMenu=new ol,this._objectContextMenu=new rl,this.viewer.cameraControl.on("rightClick",(e=>{const t=e.event,i=this.viewer.scene.pick({canvasPos:[t.offsetX,t.offsetY]});i&&i.entity.isObject?(this._canvasContextMenu.hide(),this._objectContextMenu.context={viewer:this.viewer,bimViewer:this,showObjectInExplorers:e=>{const t=this.getOpenTab();"objects"!==t&&"classes"!==t&&"storeys"!==t&&this.openTab("objects"),this.showObjectInExplorers(e)},entity:i.entity},this._objectContextMenu.show(t.pageX,t.pageY)):(this._objectContextMenu.hide(),this._canvasContextMenu.context={viewer:this.viewer,bimViewer:this},this._canvasContextMenu.show(t.pageX,t.pageY))}))}_initConfigs(){this.setConfigs({cameraNear:"0.05",cameraFar:"3000.0",smartPivot:"true",saoEnabled:"true",pbrEnabled:"false",saoBias:"0.5",saoIntensity:"0.15",saoNumSamples:"40",saoKernelRadius:"100",edgesEnabled:!0,xrayContext:!0,backgroundColor:[1,1,1],objectColorSource:"model",externalMetadata:!1})}setConfigs(e){for(let t in e)if(e.hasOwnProperty(t)){const i=e[t];this.setConfig(t,i)}}setConfig(e,t){function i(e){return!0===e||"true"===e}try{switch(e){case"backgroundColor":const s=t;this.setBackgroundColor(s),this._configs[e]=s;break;case"cameraNear":const r=parseFloat(t);this.viewer.scene.camera.perspective.near=r,this.viewer.scene.camera.ortho.near=r,this._configs[e]=r;break;case"cameraFar":const o=parseFloat(t);this.viewer.scene.camera.perspective.far=o,this.viewer.scene.camera.ortho.far=o,this._configs[e]=o;break;case"smartPivot":this.viewer.cameraControl.smartPivot=this._configs[e]=i(t);break;case"saoEnabled":this._fastNavPlugin.saoEnabled=this._configs[e]=i(t);break;case"saoBias":this.viewer.scene.sao.bias=parseFloat(t);break;case"saoIntensity":this.viewer.scene.sao.intensity=parseFloat(t);break;case"saoKernelRadius":this.viewer.scene.sao.kernelRadius=this._configs[e]=parseFloat(t);break;case"saoNumSamples":this.viewer.scene.sao.numSamples=this._configs[e]=parseFloat(t);break;case"saoBlur":this.viewer.scene.sao.blur=this._configs[e]=i(t);break;case"edgesEnabled":this._fastNavPlugin.edgesEnabled=this._configs[e]=i(t);break;case"pbrEnabled":this._fastNavPlugin.pbrEnabled=this._configs[e]=i(t);break;case"viewFitFOV":this.viewer.cameraFlight.fitFOV=this._configs[e]=parseFloat(t);break;case"viewFitDuration":this.viewer.cameraFlight.duration=this._configs[e]=parseFloat(t);break;case"perspectiveFOV":this.viewer.camera.perspective.fov=this._configs[e]=parseFloat(t);break;case"excludeUnclassifiedObjects":this._configs[e]=i(t);break;case"objectColorSource":this.setObjectColorSource(t),this._configs[e]=t;break;case"xrayContext":this._configs[e]=t;break;case"externalMetadata":this._configs[e]=i(t);break;default:this.error("setConfig() - unsupported configuration: '"+e+"'")}}catch(t){this.error("setConfig() - failed to configure '"+e+"': "+t)}}getConfig(e){return this._configs[e]}getProjectsInfo(e,t){e?this.server.getProjects(e,(e=>{this.error("getProjectsInfo() - "+e),t&&t(e)})):this.error("getProjectsInfo() - Argument expected: 'done'")}getProjectInfo(e,t,i){e?t?this.server.getProject(e,t,(e=>{this.error("getProjectInfo() - "+e),i&&i(e)})):this.error("getProjectInfo() - Argument expected: 'done'"):this.error("getProjectInfo() - Argument expected: projectId")}getObjectInfo(e,t,i,s,r){e?t?i?s?this.server.getObjectInfo(e,t,i,s,(e=>{r&&r(e)})):this.error("getProjectInfo() - Argument expected: 'done'"):this.error("getObjectInfo() - Argument expected: objectId"):this.error("getObjectInfo() - Argument expected: modelId"):this.error("getObjectInfo() - Argument expected: projectId")}loadProject(e,t,i){e?this._modelsExplorer.loadProject(e,(()=>{t&&t()}),(e=>{this.error("loadProject() - "+e),i&&i(e)})):this.error("loadProject() - Argument expected: objectId")}unloadProject(){this._modelsExplorer.unloadProject(),this.openTab("models"),this.setControlsEnabled(!1)}getLoadedProjectId(){return this._modelsExplorer.getLoadedProjectId()}getModelIds(){return this._modelsExplorer.getModelIds()}loadModel(e,t,i){e?this._modelsExplorer.loadModel(e,(()=>{t&&t()}),(e=>{this.error("loadModel() - "+e),i&&i(e)})):this.error("loadModel() - Argument expected: modelId")}loadAllModels(e=function(){}){const t=this._modelsExplorer.getModelIds(),i=(e,s)=>{if(e>=t.length)s();else{const r=t[e];this._modelsExplorer.isModelLoaded(r)?i(e+1,s):this._modelsExplorer.loadModel(r,(()=>{i(e+1,s)}),(t=>{this.error("loadAllModels() - "+t),i(e+1,s)}))}};i(0,e)}getLoadedModelIds(){return this._modelsExplorer._getLoadedModelIds()}isModelLoaded(e){if(e)return this._modelsExplorer.isModelLoaded(e);this.error("unloadModel() - Argument expected: modelId")}unloadModel(e){e?this._modelsExplorer.unloadModel(e):this.error("unloadModel() - Argument expected: modelId")}unloadAllModels(){this._modelsExplorer.unloadAllModels()}editModel(e){this.fire("editModel",{modelId:e})}deleteModel(e){this.fire("deleteModel",{modelId:e})}addModel(){this.fire("addModel",{})}setBackgroundColor(e){this.viewer.scene.canvas.backgroundColor=e}setObjectColorSource(e){switch(e){case"model":case"viewer":break;default:return e="model",void this.error("setObjectColorSource() - Unsupported value - accepted values are 'model' and 'viewer' - defaulting to 'model'")}this._objectColorSource=e}getObjectColorSource(){return this._objectColorSource||"model"}setViewerState(e,t=(()=>{})){e.tabOpen&&this.openTab(e.tabOpen),e.expandObjectsTree&&this._objectsExplorer.expandTreeViewToDepth(e.expandObjectsTree),e.expandClassesTree&&this._classesExplorer.expandTreeViewToDepth(e.expandClassesTree),e.expandStoreysTree&&this._storeysExplorer.expandTreeViewToDepth(e.expandStoreysTree),e.setCamera&&this.setCamera(e.setCamera),this._parseSelectedStorey(e,(()=>{this._parseThreeDMode(e,(()=>{t()}))}))}_parseSelectedStorey(e,t){e.selectedStorey?(this.selectStorey(e.selectedStorey),t()):t()}_parseThreeDMode(e,t){const i=!1!==e.threeDActive;this.set3DEnabled(i,t)}showObjectInExplorers(e){e?(this._objectsExplorer.showNodeInTreeView(e),this._classesExplorer.showNodeInTreeView(e),this._storeysExplorer.showNodeInTreeView(e)):this.error("showObjectInExplorers() - Argument expected: objectId")}unShowObjectInExplorers(){this._objectsExplorer.unShowNodeInTreeView(),this._classesExplorer.unShowNodeInTreeView(),this._storeysExplorer.unShowNodeInTreeView()}setObjectsVisible(e,t){this._withObjectsInSubtree(e,(e=>{e.visible=t}))}setAllObjectsVisible(e){e?this.viewer.scene.setObjectsVisible(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsVisible(this.viewer.scene.visibleObjectIds,!1)}setObjectsXRayed(e,t){this._withObjectsInSubtree(e,(e=>{e.xrayed=t}))}setAllObjectsXRayed(e){e?this.viewer.scene.setObjectsXRayed(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsXRayed(this.viewer.scene.xrayedObjectIds,!1)}setObjectsSelected(e,t){this._withObjectsInSubtree(e,(e=>{e.selected=t}))}setAllObjectsSelected(e){e?this.viewer.scene.setObjectsSelected(this.viewer.scene.objectIds,!0):this.viewer.scene.setObjectsSelected(this.viewer.scene.selectedObjectIds,!1)}_withObjectsInSubtree(e,t){if(e)for(let i=0,s=e.length;i<s;i++){const s=e[i];this.viewer.metaScene.withMetaObjectsInSubtree(s,(e=>{const i=this.viewer.scene.objects[e.id];i&&t(i)}))}else this.error("Argument expected: objectIds")}flyToObject(e,t){if(!e)return void this.error("flyToObject() - Argument expected: objectId");const i=this.viewer,s=i.scene,r=[];if(this.viewer.metaScene.withMetaObjectsInSubtree(e,(e=>{s.objects[e.id]&&r.push(e.id)})),0===r.length)return this.error("Object not found in viewer: '"+e+"'"),void(t&&t());s.setObjectsVisible(r,!0),s.setObjectsHighlighted(r,!0);const o=s.getAABB(r);i.cameraFlight.flyTo({aabb:o},(()=>{t&&t(),setTimeout((function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)}),500)})),i.cameraControl.pivotPos=u.getAABB3Center(o)}viewFitObjects(e,t){if(!e)return void this.error("flyToObject() - Argument expected: objectIds");const i=this.viewer,s=i.scene,r=[];for(var o=0,a=e.length;o<a;o++){const t=e[o];this.viewer.metaScene.withMetaObjectsInSubtree(t,(e=>{s.objects[e.id]&&r.push(e.id)}))}if(0===r.length)return void(t&&t());s.setObjectsVisible(r,!0),s.setObjectsHighlighted(r,!0);const n=s.getAABB(r);i.cameraFlight.flyTo({aabb:n},(()=>{t&&t(),setTimeout((function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)}),500)})),i.cameraControl.pivotPos=u.getAABB3Center(n)}viewFitAll(e){const t=this.viewer,i=t.scene.getAABB();t.cameraFlight.flyTo({aabb:i},(()=>{e&&e()})),t.cameraControl.pivotPos=u.getAABB3Center(i)}jumpToObject(e){if(!e)return void this.error("jumpToObject() - Argument expected: objectId");const t=this.viewer,i=t.scene,s=[];if(this.viewer.metaScene.withMetaObjectsInSubtree(e,(e=>{i.objects[e.id]&&s.push(e.id)})),0===s.length)return void this.error("Object not found in viewer: '"+e+"'");i.setObjectsVisible(s,!0);const r=i.getAABB(s);t.cameraFlight.jumpTo({aabb:r}),t.cameraControl.pivotPos=u.getAABB3Center(r)}setCamera(e){const t=this.viewer.scene.camera;e.eye&&(t.eye=e.eye),e.look&&(t.look=e.look),e.up&&(t.up=e.up)}viewFitModels(e,t){if(!e)return void this.error("viewFitModels() - Argument expected: modelIds");const i=this.viewer,s=i.scene,r=u.AABB3();u.collapseAABB3(r);for(var o=0,a=e.length;o<a;o++){const t=e[o],i=s.models[t];i?(i.visible=!0,i.highlighted=!0,u.expandAABB3(r,i.aabb)):this.error("Model not found in viewer: '"+t+"'")}t?i.cameraFlight.flyTo({aabb:r},(()=>{t(),setTimeout((function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)}),500)})):(i.cameraFlight.jumpTo({aabb:r}),setTimeout((function(){s.setObjectsHighlighted(s.highlightedObjectIds,!1)}),500)),i.cameraControl.pivotPos=u.getAABB3Center(r)}openTab(e){if(!e)return void this.error("openTab() - Argument expected: tabId");const t="active";let i;switch(e){case"models":i="xeokit-modelsTab";break;case"objects":i="xeokit-objectsTab";break;case"classes":i="xeokit-classesTab";break;case"storeys":i="xeokit-storeysTab";break;default:return void this.error("openTab() - tab not recognized: '"+e+"'")}let s=this._explorerElement.querySelectorAll(".xeokit-tab"),r=this._explorerElement.querySelector("."+i);for(let e=0;e<s.length;e++){let i=s[e];i.isEqualNode(r)?i.classList.add(t):i.classList.remove(t)}}getOpenTab(){function e(e,t){return!!e&&(" "+e.className+" ").indexOf(" "+t+" ")>-1}const t="active";return e(this._explorerElement.querySelector(".xeokit-modelsTab"),t)?"models":e(this._explorerElement.querySelector(".xeokit-objectsTab"),t)?"objects":e(this._explorerElement.querySelector(".xeokit-classesTab"),t)?"classes":e(this._explorerElement.querySelector(".xeokit-storeysTab"),t)?"storeys":"none"}set3DEnabled(e,t){this._threeDMode.setActive(e,t)}get3DEnabled(){return this._threeDMode.getActive()}setOrthoEnabled(e,t){this._orthoMode.setActive(e,t)}getOrthoEnabled(){return this._orthoMode.getActive()}selectStorey(e,t){const i=this.viewer.metaScene.metaObjects[e];i?"IfcBuildingStorey"===i.type?this._storeysExplorer.selectStorey(e,t):this.error("selectStorey() - Object is not an IfcBuildingStorey: '"+e+"'"):this.error("selectStorey() - Object is not found: '"+e+"'")}saveBCFViewpoint(e){return this._bcfViewpointsPlugin.getViewpoint(e)}loadBCFViewpoint(e,t){e?(this._bcfViewpointsPlugin.setViewpoint(e,t),this._orthoMode.setActive("ortho"===this.viewer.camera.projection)):this.error("loadBCFViewpoint() - Argument expected: bcfViewpoint")}resetView(){this._resetAction.reset()}setControlsEnabled(e){this._objectsExplorer.setEnabled(e),this._classesExplorer.setEnabled(e),this._storeysExplorer.setEnabled(e),this._resetAction.setEnabled(e),this._fitAction.setEnabled(e),this._threeDMode.setEnabled(e),this._orthoMode.setEnabled(e),this._firstPersonMode.setEnabled(e),this._queryTool.setEnabled(e),this._hideTool.setEnabled(e),this._selectionTool.setEnabled(e),this._sectionTool.setEnabled(e)}setKeyboardEnabled(e){this.viewer.scene.input.keyboardEnabled=e}getKeyboardEnabled(){return this.viewer.scene.input.keyboardEnabled}clearSections(){this._sectionTool.clear()}flipSections(){this._sectionTool.flipSections()}hideSectionEditControl(){this._sectionTool.hideControl()}getNumSections(){return this._sectionTool.getNumSections()}destroy(){this.viewer.destroy(),this._bcfViewpointsPlugin.destroy(),this._canvasContextMenu.destroy(),this._objectContextMenu.destroy()}}export{nl as BIMViewer,Sn as Server};
